package main
import (
"fmt"
)
type bar struct {
}
func (b bar) String() string {
return "bar"
}
type foo struct {
b []*bar
bb *bar
}
func main() {
f := foo{b: []*bar{&bar{}}, bb:&bar{}}
fmt.Println(f, f.b, f.bb)
}
Why the result is
{[0x176f44] 0x176f44} [bar] bar
Not
{[bar] bar} [bar] bar
Are there any reasons behind it? It seems easy to implement and good for readability.
You have several problems in your code. You define Stirng
on bar
which is unexported, your fields are unexported as well. This works:
type Bar struct {
}
func (b Bar) String() string {
return "bar"
}
type foo struct {
B []Bar
BB Bar
}
func main() {
f := foo{B: []Bar{Bar{}}, BB: Bar{}}
fmt.Println(f)
}
Playground: https://play.golang.org/p/OhoIcB7cA3.
This would also work with *Bar
.