Rust Go - gwenn/hypomnemata GitHub Wiki

Rust Go

Formatted print

println!("Hello, {:s}", "world");
import "fmt"

fmt.Printf("Hello, %s\n", "world")

Visiblity

  • pub keyword with Rust
  • Uppercase with Go

Variables

Declaration

  • let x keyword with Rust
  • optional var x keyword with Go or :=

Mutability

  • immutable by default with Rust. mut keyword.
  • no immutable variable with Go. Only constants (const) supported

Types

  • x: T with Rust
  • x T with Go

Casting

  • x as T keyword with Rust
  • x.(T) with Go

Alias

  • type AliasName name with Rust. Type aliases don't provide any extra type safety, because aliases are not new types
  • type aliasName name with 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

  • mod keyword with Rust.
  • Module can be nested.
  • Modules can be mapped to a file/directory hierarchy.
  • use keyword 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 name keyword with Go.

  • extern crate keyword with Rust.

  • import keyword with Go.

conditional build tags

  • cfg attribute with Rust.
  • // +build tags with Go or file name.

Structures

  • With Rust, there are three types that can be created using the struct keyword:
  • 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

  • trait with Rust.
  • interface with Go. there is no explicit implementation.

Raw pointer

  • raw pointer *const T or *mut T, a pointer to anything with Rust. Requires unsafe code to dereference.
  • unsafe.Pointer with Go.

Reference

A non-owning pointer to an object. Has an associated lifetime, to assert that what it points to is always valid data.