Reputation: 3948
I have the following code:
type room struct {
width float32
length float32
}
type house struct{
s := make([]string, 3)
name string
roomSzSlice := make([]room, 3)
}
func main() {
}
And when i try to build and run it i get the following errors:
c:\go\src\test\main.go:10: syntax error: unexpected :=
c:\go\src\test\main.go:11: non-declaration statement outside function body
c:\go\src\test\main.go:12: non-declaration statement outside function body
c:\go\src\test\main.go:13: syntax error: unexpected }
What did i do wrong?
Thanks!
Upvotes: 6
Views: 14980
Reputation: 235
You can also refer this: https://golangbyexample.com/struct-slice-field-go/
type student struct {
name string
rollNo int
city string
}
type class struct {
className string
students []student
}
goerge := student{"Goerge", 35, "Newyork"}
john := student{"Goerge", 25, "London"}
students := []student{goerge, john}
class := class{"firstA", []student{goerge, john}}
Upvotes: -1
Reputation: 20683
You can declare a slice in a struct declaration, but you can not initialize it. You have to do this by different means.
// Keep in mind that lowercase identifiers are
// not exported and hence are inaccessible
type House struct {
s []string
name string
rooms []room
}
// So you need accessors or getters as below, for example
func(h *House) Rooms()[]room{
return h.rooms
}
// Since your fields are inaccessible,
// you need to create a "constructor"
func NewHouse(name string) *House{
return &House{
name: name,
s: make([]string, 3),
rooms: make([]room, 3),
}
}
Please see the above as a runnable example on Go Playground
EDIT
To Initialize the struct partially, as requested in the comments, one can simply change
func NewHouse(name string) *House{
return &House{
name: name,
}
}
Please see the above as a runnable example on Go Playground, again
Upvotes: 7
Reputation: 3228
First off you cannot assign/initialize inside the struct. The := operator declares and assigns. You can however, achieve the same result simply.
Here is a simple, trivial example that would do roughly what you're trying:
type house struct {
s []string
}
func main() {
h := house{}
a := make([]string, 3)
h.s = a
}
I've never written one that way, but if it servers your purpose... it compiles anyway.
Upvotes: 7