Created
July 16, 2021 04:15
-
-
Save dmh2000/9f84b836a193b74eb2f3db2388511748 to your computer and use it in GitHub Desktop.
Lists of resolvers in graph-gophers/graphql-go - funny behavior because pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// when you get a list of objects to resolve, you create a slice of resolvers for each | |
// element in the list of objects. But be careful how you structure your loops because | |
// there are a log of pointers to pointers etc | |
func (*rootResolver) TeamsByNickname(args struct{ Nickname string }) *[]*teamResolver { | |
// assume teams = slice of objects from a database | |
// create a list of resolvers : the right way | |
// this is ok because it gives a pointer to elements of the slice | |
var tr []*teamResolver = make([]*teamResolver, len(teams)) | |
for i := range teams { | |
tr[i] = &teamResolver{&teams[i]} | |
fmt.Println(i, tr[i].t) | |
} | |
// create a list of resolvers the wrong way | |
// this will fail because it generates pointers to the same object for the resolver | |
var tx []*teamResolver = make([]*teamResolver, len(teams)) | |
for i,t := range teams { | |
tx[i] = &teamResolver{&t} | |
fmt.Println(i, tx[i].t) // this will print ok because at this point &t points to the current value | |
} | |
// tx | |
// at this point, &t points to teams[last] for all the elements in tx | |
return &tr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment