给字符串解引用运算符赋值

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年2月21日 15:40:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42361324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定