FAQ - Help and questions

How do Go interfaces and struct embedding map to Rust traits and composition?

#porting#golang#traitspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A Go type satisfies an interface just by having the methods, with no declaration. A Rust type must say impl Trait for Type, which also lets you implement a trait for a type you did not write. Go embedding becomes a field plus forwarding methods, or Deref for a real wrapper type.

Checked with rustc 1.93.0, Go 1.26.5, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

GoRust
type Shape interface { Area() float64 }trait Shape { fn area(&self) -> f64; }
a type with the method satisfies it silentlyimpl 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):

go
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())
}
text
area 9
base #4

Rust (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:

src/main.rsrust
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());
}
text
area 9
base #4 (x)
base #9

Note 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#

  1. For each Go interface, write a trait with the same methods. Keep traits small, as in Go: one to three methods.
  2. For each type that satisfied it, add impl Trait for Type. Search the Go code for assignments to the interface type to find them.
  3. Where a Go function took an interface parameter, choose: a generic (T: Trait) when callers know the type, or &dyn Trait when you need run-time choice (see the thread on trait objects).
  4. 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 Deref or just a public field.
  5. Replace type switches by an enum when you control the types, so that match checks every case is handled.

Common mistakes#

  • Using Deref to 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet