Answer#
Go interfaces are satisfied structurally: if a type has the methods, it implements the interface, and nobody writes "implements". Rust traits are satisfied nominally: there must be an impl Trait for Type item somewhere. The extra line has a benefit. It can be written by someone other than the author of the type (for your own trait on a standard type, or a standard trait on your own type), and the compiler can check that all methods exist and that no two implementations conflict.
Go has no inheritance either, but it allows embedding: a struct that contains another struct by name has the inner struct's methods promoted to itself. Rust does not promote methods automatically.
| Go | Rust |
|---|---|
type Shape interface { Area() float64 } | trait Shape { fn area(&self) -> f64; } |
| a type with the method satisfies it silently | impl Shape for Sq { ... } |
var s Shape = Sq{3} | let s: &dyn Shape = &Sq(3.0) or Box<dyn Shape> |
func f(s Shape) | fn f(s: &dyn Shape) or fn f<T: Shape>(s: &T) |
empty interface any / interface{} | a generic T, or an enum; dyn Any only when you must |
embedding type Named struct { Base } | a field base: Base and forwarding methods; Deref for wrapper types |
type switch switch v := x.(type) | match on an enum |
Go (1.26.5):
type Shape interface{ Area() float64 }
type Sq struct{ s float64 }
func (q Sq) Area() float64 { return q.s * q.s } // no "implements" anywhere
type Base struct{ id int }
func (b Base) Describe() string { return fmt.Sprintf("base #%d", b.id) }
type Named struct {
Base
label string
}
func main() {
var s Shape = Sq{3}
fmt.Println("area", s.Area())
n := Named{Base{4}, "x"}
fmt.Println(n.Describe())
}area 9
base #4Rust (1.93.0). The Named type forwards by hand, and Wrapper uses Deref so that the inner type's methods can be called on it:
use std::ops::Deref;
trait Shape {
fn area(&self) -> f64;
}
struct Sq(f64);
// Go decides that Sq is a Shape because it has an Area method. Rust needs this line, on purpose.
impl Shape for Sq {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn describe(s: &dyn Shape) -> String {
format!("area {}", s.area())
}
struct Base {
id: u32,
}
impl Base {
fn describe(&self) -> String {
format!("base #{}", self.id)
}
}
// Rust: hold the other type as a field and forward what you want to expose...
struct Named {
base: Base,
label: String,
}
impl Named {
fn describe(&self) -> String {
format!("{} ({})", self.base.describe(), self.label)
}
}
// ...or, for a true wrapper type, implement Deref (not a general replacement for inheritance).
struct Wrapper(Base);
impl Deref for Wrapper {
type Target = Base;
fn deref(&self) -> &Base {
&self.0
}
}
fn main() {
println!("{}", describe(&Sq(3.0)));
println!("{}", Named { base: Base { id: 4 }, label: "x".into() }.describe());
println!("{}", Wrapper(Base { id: 9 }).describe());
}area 9
base #4 (x)
base #9Note that Named::describe in the Rust version had to be written, and that is where it also adds the label; in Go the promoted Describe ignored the label. Making forwarding explicit forces the question each time: should the outer type behave exactly like the inner one, or add something?
How to do it#
- For each Go interface, write a trait with the same methods. Keep traits small, as in Go: one to three methods.
- For each type that satisfied it, add
impl Trait for Type. Search the Go code for assignments to the interface type to find them. - Where a Go function took an interface parameter, choose: a generic (
T: Trait) when callers know the type, or&dyn Traitwhen you need run-time choice (see the thread on trait objects). - For embedding, ask what the embedding is for. To reuse data and some methods, use a field and forward. To make a transparent wrapper (a newtype), use
Derefor just a public field. - Replace type switches by an
enumwhen you control the types, so thatmatchchecks every case is handled.
Common mistakes#
- Using
Derefto imitate inheritance among unrelated types. It works for smart pointers and wrappers, and confuses readers elsewhere. - Adding a method to a Go interface and not noticing which types break: in Rust the compiler lists them.
- Forgetting the "orphan rule": you can implement a trait for a type only if your crate defines the trait or the type.
Related questions#
Does Rust have Go's Stringer interface?#
The traits Display and Debug play that role: implement fmt::Display to be printable with {}.
What replaces an interface holding a nil pointer?#
Option<Box<dyn Trait>>. A Box is never null, so the "interface that is non-nil but holds nil" trap of Go does not exist.
Sources#
- The Rust Book, "Traits: Defining Shared Behavior": https://doc.rust-lang.org/book/ch10-02-traits.html
- The Go Programming Language Specification, "Interface types": https://go.dev/ref/spec#Interface_types