Rust Go - gwenn/hypomnemata GitHub Wiki
Rust Go
Formatted print
println!("Hello, {:s}", "world");
import "fmt"
fmt.Printf("Hello, %s\n", "world")
Visiblity
pubkeyword with Rust- Uppercase with Go
Variables
Declaration
let xkeyword with Rust- optional
var xkeyword with Go or:=
Mutability
- immutable by default with Rust.
mutkeyword. - no immutable variable with Go. Only constants (
const) supported
Types
x: Twith Rustx Twith Go
Casting
x as Tkeyword with Rustx.(T)with Go
Alias
type AliasName namewith Rust. Type aliases don't provide any extra type safety, because aliases are not new typestype aliasName namewith Go. The new type is different from the existing type.
newtype struct A tuple structure with a single unnamed field. For example struct NodeIndex(int). Useful to create wrapper types.
Inference
Both Rust and Go support type inference.
Functions
fun f(x: T, ...) -> T { }with Rust. Functions can use tuples to return multiple values.func f(x T, ...) T { }with Go. Go supports multiple return values
Module
modkeyword with Rust.
- Module can be nested.
- Modules can be mapped to a file/directory hierarchy.
usekeyword with Rust (optional) or full path.
Crate
Rust's compilation unit, a single library or executable. Is the root of a namespace.
Rust crate is more like Go module.
-
#![crate_id = "name#0.1"]with Rust. -
package namekeyword with Go. -
extern cratekeyword with Rust. -
importkeyword with Go.
conditional build tags
cfgattribute with Rust.// +build tagswith Go or file name.
Structures
- With Rust, there are three types that can be created using the
structkeyword:
- Tuple structs
struct Pair(int, f64), which are, basically, named tuples. structs declared without named fields. - The classic C structs
struct Point {x: f64, y: f64}, record structs, structs declared with named fields. - Unit structs
struct Nil, which are field-less structs. A struct that only has one value. Works just the same as the unit type (), except it is a distinct type.
- With Go, there is only C like structs
type Point struct{ x, y float64 }.
Polymorphism
traitwith Rust.interfacewith Go. there is no explicit implementation.
Raw pointer
- raw pointer
*const Tor*mut T, a pointer to anything with Rust. Requires unsafe code to dereference. unsafe.Pointerwith Go.
Reference
A non-owning pointer to an object. Has an associated lifetime, to assert that what it points to is always valid data.