package main
import (
"fmt"
)
type set map[string]struct{}
var validSub set
func init() {
validSub.Init([]string{"aa", "bb", "cc"})
fmt.Printf("%+v\n", validSub)
}
func (s set) Init(slice []string) {
s = make(map[string]struct{}, len(slice))
for _, s1 := range slice {
s[s1] = struct{}{}
}
}
func (s set) Has(a string) bool { _, ok := s[a]; return ok }
func main() {
fmt.Println(validSub.Has("aa"))
fmt.Println(validSub.Has("dd"))
}
Assigning a value to the receiver will only affect local variable.
Try pointer receiver.
--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/rssS79X7aUs/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
This is (more or less) the same problem with value receiver.
However, map is a reference type, so once the map has been created you really can use value receiver : https://play.golang.org/p/FePU2I-u2-
If your concern is about "allocating a map with make, exactly the size of the input slice", then consider that the "constructor-like" idiom in go is a function NewSet, not a method :
https://play.golang.org/p/6H1ThzyhbM
Writing all this on smartphone is possible but tedious and error-prone!
Even in OO style (e.g. java), you would not be able to write
Set s = null;
s.init( list(1,2,3) );
This is (more or less) the same problem with value receiver... the "constructor-like" idiom in go is a function NewSet, not a method :
https://play.golang.org/p/_n56yMhlRt
map is a reference type
No penalty, passing a map around never copies the values.
But a "pointer to a pointer" receiver is not strictly the same as a pointer receiver.
--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/rssS79X7aUs/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.