英文:
The go-compiler reports variable declared but not used when using pointers
问题
我有一段代码,但我不明白为什么Go编译器报告一个变量被声明但未使用:
package main
import "fmt"
func main() {
var StringSlice []*string
MyStr0 := "Zero"
StringSlice = append(StringSlice, &MyStr0)
MyStr1 := "One"
StringSlice = append(StringSlice, &MyStr1)
MyStr2 := "Two"
StringSlice = append(StringSlice, &MyStr2)
var StrPtr *string
for i, Value := range StringSlice {
fmt.Println(Value)
if i == 1 {
StrPtr = Value
}
} // END for
}
当注释掉Printf语句后,Go编译器报告"./prog.go:15:6: StrPtr declared but not used",你可以在go-playground上的示例中查看:https://go.dev/play/p/J3p4NDR6fBm
当注释掉Printf语句后,一切都正常,甚至在StrPtr中存储了正确的字符串指针...
非常感谢您的帮助!
英文:
I have a snippet of code that i am unable to understand why the go compiler is reporting that a variable is declared but not used:
package main
import "fmt"
func main() {
var StringSlice []*string
MyStr0 := "Zero"
StringSlice = append(StringSlice, &MyStr0)
MyStr1 := "One"
StringSlice = append(StringSlice, &MyStr1)
MyStr2 := "Two"
StringSlice = append(StringSlice, &MyStr2)
var StrPtr *string
for i, Value := range StringSlice {
fmt.Println(Value)
if i == 1 {
StrPtr = Value
}
} // END for
With the Printf statement commented out, the go compiler claims »./prog.go:15:6: StrPtr declared but not used« - see the example in the go-playground at: https://go.dev/play/p/J3p4NDR6fBm
When the Printf is commented out, everything is fine and there's even the correct string-pointer stored in StrPtr…
Thank you very much in advance for your help!
答案1
得分: 1
问题在于你没有使用StrPtr
。你重新分配了它,但它从未被读取。如果你将它添加到Printf语句中,错误将消失。
package main
import "fmt"
func main() {
var StringSlice []*string
MyStr0 := "Zero"
StringSlice = append(StringSlice, &MyStr0)
MyStr1 := "One"
StringSlice = append(StringSlice, &MyStr1)
MyStr2 := "Two"
StringSlice = append(StringSlice, &MyStr2)
var StrPtr *string
for i, Value := range StringSlice {
fmt.Println(Value)
if i == 1 {
StrPtr = Value
fmt.Println(StrPtr) // <--- 添加这行
}
} // 结束for循环
}
英文:
The problem is that you are not using StrPtr
. You are reassigning it, but it is never read. If you add that to a Printf statement the error will go away.
package main
import "fmt"
func main() {
var StringSlice []*string
MyStr0 := "Zero"
StringSlice = append(StringSlice, &MyStr0)
MyStr1 := "One"
StringSlice = append(StringSlice, &MyStr1)
MyStr2 := "Two"
StringSlice = append(StringSlice, &MyStr2)
var StrPtr *string
for i, Value := range StringSlice {
fmt.Println(Value)
if i == 1 {
StrPtr = Value
fmt.Println(StrPtr) // <--- add this
}
} // END for
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论