I have this code
package main
import (
"fmt"
)
type foo struct {
a int
b bool
}
type foos []foo
type bar struct {
foos
}
func newBar() *bar {
b := &bar{
foos: make([]foo, 3, 3),
}
for _, foo := range b.foos {
// didn't set b to true
foo.b = true
}
return b
}
func main() {
b := newBar()
fmt.Println(b)
// set b to true
b.foos[0].b = true
fmt.Println(b)
}
As you can see I want to initialize bar
using constructor newBar()
but I want the embed type foo.b is initialize with non zero value so I initialize with for range statement but it didn't work as intended, the foo.b
is still false, all of them. As comparison in the main function using this code b.foos[0].b = true
it work. So whats wrong with my code?
Omg, I just realized this after posting this question, it's because variable slot
is local to for loop
. So the solution is:
for i, _ := range b.foos {
// now b is set to true
b.foos[i].b = true
}