我有一种类型的 struct ,需要从另一个函数中更改其值.函数SetPath()
使用一个指向我要更改的字符串的指针和另一个指向我要使用的默认值的指针.调用函数时,我可以向它传递 struct 中字符串的地址,但不能传递指针或定义默认值的常量的地址.
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)
}
上面代码中的问题是main()
的最后一行-如何将指针传递给常数DefaultFileName
,以便在SetPath()
中使用其值?我的编辑们抱怨这个常数,但不是&settings.FilePath
.
我相信一个解决方案是将函数签名更改为如下内容:
func SetPath(path *string, defaultPath string)
但我真的很想更多地理解指针,我觉得这是一个很好的机会来了解我应该在何时、何地以及如何使用它们,特别是因为优化内存使用在这个项目中很重要.