I am struggling with the initiation of a slice in a struct (GO-language). This may be easy, but still I can not solve it. I get below error
./prog.go:11:1: syntax error: unexpected var, expecting field name or embedded type
./prog.go:25:2: no new variables on left side of :=
./prog.go:26:2: non-name g.s on left side of :=
I believe that s
should be declared as part of the struct, so I wonder why I get that error. Someone got some advice?
package main
import "fmt"
type node struct {
value int
}
type graph struct {
nodes, edges int
s []int
}
func main() {
g := graphCreate()
}
func input(tname string) (number int) {
fmt.Println("input a number of " + tname)
fmt.Scan(&number)
return
}
func graphCreate() (g graph) {
g := graph{input("nodes"), input("edges")}
g.s = make([]int, 100)
return
}
We can use the new keyword when declaring a struct. Then we can assign values using dot notation to initialize it.
The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.
To add an element to a slice , you can use Golang's built-in append method. append adds elements from the end of the slice. The first parameter to the append method is a slice of type T . Any additional parameters are taken as the values to add to the given slice .
slice is a composite data type and because it is composed of primitive data type (see variables lesson for primitive data types). Syntax to define a slice is pretty similar to that of an array but without specifying the elements count. Hence s is a slice.
You have a few errors :
g.s
is already defined by the type graph
when g
is of type graph
. So it's not a "new variable"var
inside a type declarationg
already declared (as a return type) in your graphCreate
functionhere's a compiling code :
package main
import "fmt"
type node struct {
value int
}
type graph struct {
nodes, edges int
s []int // <= there was var here
}
func main() {
graphCreate() // <= g wasn't used
}
func input(tname string) (number int) {
fmt.Println("input a number of " + tname)
fmt.Scan(&number)
return
}
func graphCreate() (g graph) { // <= g is declared here
g = graph{nodes:input("nodes"), edges:input("edges")} // <= name the fields
g.s = make([]int, 100) // <= g.s is already a known name
return
}
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