I have a type of struct for which I need to change its values from another function. The function SetPath()
takes a pointer to the string I want to change and another pointer to the default value I want to use. When I call the function, I can pass it the address of the string in the struct, but I cannot pass it a pointer or the address of a const that defines the default value.
package main
const DefaultFileName string = "default.config"
type Settings struct {
FilePath string
}
func SetPath(path, defaultPath *string) {
if *path == "" {
*path = *defaultPath
}
}
func main() {
settings := new(Settings)
SetPath(&settings.FilePath, &DefaultFileName)
}
The problem in the code above is the last line of main()
- how do I pass a pointer to the constant DefaultFileName
so I can use its value in SetPath()
? My editors complain about the constant, but not about &settings.FilePath
.
I'm sure a solution could be to change the function signature to something like:
func SetPath(path *string, defaultPath string)
But I really want to understand pointers more and I feel like this is a good opportunity to learn more about when, where, and how I should be using them - especially since optimizing memory usage is important in this project.
CodePudding user response:
You can't take the address of constants, for details see Find address of constant in go.
But you don't need to. SetPath()
only wants to modify path
, but not defaultPath
, so defaultPath
doesn't need to be a pointer, in fact it's clearer if it's not.
func SetPath(path *string, defaultPath string) {
if *path == "" {
*path = defaultPath
}
}
And calling it:
SetPath(&settings.FilePath, DefaultFileName)