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!
To declare the type for a variable that holds a slice, use an empty pair of square brackets, followed by the type of elements the slice will hold.
A slice struct is composed of zerothElement pointer which points to the first element of an array that slice references. len and cap is the length and capacity of a slice respectively. type is the type of elements that underneath (referenced) array is composed of.
In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct. Here, you can see the two different structs, and the employee struct is used as an array in the company struct.
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With