Answer the question
In order to leave comments, you need to log in
Structures, pointers, arrays?
Greetings Toaster Members!
Please explain some things. So I need to make an array of structures, and each element of the array had an action, there seems to be some kind of magic with pointers, which I haven’t felt yet. In general code:
package main
import "fmt"
type nextWords struct {
words []string
}
func (nw *nextWords) GetFirstItem() string {
return nw.words[0]
}
func main() {
var myMap = make(map[string]nextWords)
myMap["hello"] = nextWords{words: []string{"foo", "bar"}}
fmt.Println(myMap["hello"].GetFirstItem())
}
C:\Windows\system32\cmd.exe /c (go run test1.go ^& pause)
# command-line-arguments
.\test1.go:18: cannot call pointer method on myMap["hello"]
.\test1.go:18: cannot take the address of myMap["hello"]
Для продолжения нажмите любую клавишу . . .
Answer the question
In order to leave comments, you need to log in
In this case, you need to put pointers to your structure in the map.
https://play.golang.org/p/Jn18TTSDh5T
package main
import "fmt"
type nextWords struct {
words []string
}
func (nw *nextWords) GetFirstItem() string {
return nw.words[0]
}
func main() {
var myMap = make(map[string]*nextWords)
myMap["hello"] = &nextWords{words: []string{"foo", "bar"}}
fmt.Println(myMap["hello"].GetFirstItem())
}
Alright, thanks for the detailed explanation!
It turns out that you need to create an array of pointers to the nextWords structure.
unless we first pull it out of the map into a variable and call a method on it
By the way, I just managed to do this, based on this I wanted to make a call (&myMap["hello"]).GetFirstItem() of this kind, but the file also came out
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question