我第一次使用指针,我有一个简单的问题.
我有两个函数main和other.如果我在main函数中有一个我想在函数中使用的变量,我other应该将它作为参数传递还是击败指针的对象?
选项1
func main() {
myVar := "hello world"
other(&myVar)
}
func other(s *string) {
println(s)
}
Run Code Online (Sandbox Code Playgroud)
方案2
func main() {
myVar := "hello world"
other()
}
func other() {
println(*myVar) //Is myVar even accessible here?
}
Run Code Online (Sandbox Code Playgroud)
不确定为什么你被downvoted ...第二个选项将无法编译,因为在其他函数内部myVar不存在.每个变量都有一个范围.该变量只能在其范围内访问.
(如果你想了解更多关于不同范围的信息,我推荐以下链接https://www.golang-book.com/books/web/01-02 - 向下滚动到范围.这是一个很好的可视化解释.)
为了使事情更清楚,我添加了一些例子:
选项1 - 传递指针值
这就是你所拥有的.但请确保取消引用指针以获取实际字符串.您的版本是打印指针本身(mem-address).看到我的变化(*s而不仅仅是s)!
func main() {
myVar := "hello world"
other(&myVar)
}
func other(s *string) {
println(*s)
}
Run Code Online (Sandbox Code Playgroud)
选项2 - 传递变量值
这可能就是您对选项2的意思.
package main
func main() {
myVar := "hello world"
other(myVar)
}
func other(myVar string) {
println(myVar)
}
Run Code Online (Sandbox Code Playgroud)
选项3 - 使myVar全球化
也许这就是你想要在第二个选项中做的事情.myVar在这里是全局的(或者在golang lingo中,myVar有一个包级别范围),因此可以在其他函数内部访问.
var myVar = "hello world"
func main() {
other()
}
func other() {
println(myVar)
}
Run Code Online (Sandbox Code Playgroud)
至于你的问题,你应该传递值或指向变量的指针:
通常,如果您的函数需要能够编辑值,则传递指针.此外,当变量本身非常大并且需要花费时间/资源来传递值时,您可以传递更有效的指针.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |