英文:
Assign value to a string dereference operator
问题
我是你的中文翻译助手,以下是代码的翻译:
package main
import "fmt"
func main() {
course := "Docker深入解析"
changeCourse(&course)
}
func changeCourse(course *string) {
fmt.Println(course) // 打印course的内存地址,因为它是一个指针
fmt.Println(*course) // 打印值,因为*表示解引用指针
// 问题
*course = "扩展的Docker" // *course是一个字符串,这里的赋值是如何工作的
fmt.Println(*course) // 打印"扩展的Docker"
}
希望对你有帮助!
英文:
I'm new to go, pardon me if this is a regular question, How does the assignment to a string dereference operator works below?
package main
import "fmt"
func main() {
course := "Docker Deep Dive"
changeCourse(&course)
}
func changeCourse(course *string) {
fmt.Println(course) // prints the memory address of course since it is a pointer
fmt.Println(*course) // prints the value since * is dereferenceing the pointer
// Issue
*course = "Docker Extended" // *course is a string, how does the assignment works here.
fmt.Println(*course) // prints "Docker Extended"
}
答案1
得分: 2
*
(也称为间接操作符)用于“解引用”指针变量,解引用指针使我们可以访问指针所指向的值。
在这种情况下:*course = "Docker Extended"
,基本上你是在告诉编译器:将字符串“Docker Extended”存储在course
所引用的内存位置中。
英文:
*
(also know as indirection operator) is used to “dereference” pointer variables, dereferencing a pointer gives us access to the value the pointer points to.
In this case: *course = "Docker Extended"
basically you are saying to the compiler: store the string
"Docker Extended" in the memory location course
refers to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论