`&Struct{}`和`Struct{}`之间的区别是什么?

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

Difference between &Struct{} vs Struct{}

问题

有没有理由我应该使用&StructName{}来创建一个结构体,而不是Struct{}?我看到很多例子都使用前一种语法,甚至在Effective Go页面中也是如此,但我真的不明白为什么要这样做。

附加说明:
我不确定我是否用这两种方法很好地解释了我的问题,所以让我进一步明确我的问题。

我知道使用&会得到一个指针而不是一个值,但我想知道为什么我要使用&StructName{}而不是StructName{}。例如,使用下面的方式有什么好处:

func NewJob(command string, logger *log.Logger) *Job {
    return &Job{command, logger}
}

而不是:

func NewJob(command string, logger *log.Logger) Job {
    return Job{command, logger}
}
英文:

Is there a reason why I should create a struct using &StructName{} instead of Struct{}? I see many examples using the former syntax, even in the Effective Go Page but I really can not understand why.

Additional Notes:
I'm not sure whether I explained my problem well with these two approaches so let me refine my question.

I know that by using the & I will recieve a pointer instead of a value however I would like to know why would I use the &StructName{} instead of the StructName{}. For example, is there any benefits of using:

func NewJob(command string, logger *log.Logger) *Job {
    return &Job{command, logger}
}

instead of:

func NewJob(command string, logger *log.Logger) Job {
    return Job{command, logger}
}

答案1

得分: 19

好的,以下是翻译好的内容:

package main
import "fmt"

type test_struct struct {
    Message string
}

func (t test_struct) Say() {
    fmt.Println(t.Message)
}

func (t test_struct) Update(m string) {
    t.Message = m
}

func (t *test_struct) SayP() {
    fmt.Println(t.Message)
}

func (t *test_struct) UpdateP(m string) {
    t.Message = m
}

func main() {
    ts := test_struct{}
    ts.Message = "test"
    ts.Say()
    ts.Update("test2")
    ts.Say() // 仍然输出 test

    tsp := &test_struct{}
    tsp.Message = "test"
    tsp.SayP()
    tsp.UpdateP("test2")
    tsp.SayP() // 输出 test2
}

你可以在这里运行它:go playground


<details>
<summary>英文:</summary>

Well, they will have different behavior. Essentially if you want to modify state using a method on a struct, then you will need a pointer, otherwise a value will be fine. Maybe an example will be better:

    package main
    import &quot;fmt&quot;



    type test_struct struct {
	  Message string
    }

    func (t test_struct)Say (){
	   fmt.Println(t.Message)
    }

    func (t test_struct)Update(m string){
	  t.Message = m; 
    }

    func (t * test_struct) SayP(){
	   fmt.Println(t.Message)
    }

    func (t* test_struct) UpdateP(m string)  {
	  t.Message = m;
    }

    func main(){
	  ts := test_struct{}
	  ts.Message = &quot;test&quot;;
	  ts.Say()
	  ts.Update(&quot;test2&quot;)
	  ts.Say() // will still output test

	  tsp := &amp;test_struct{}
	  tsp.Message = &quot;test&quot;
	  tsp.SayP();
	  tsp.UpdateP(&quot;test2&quot;)
	  tsp.SayP() // will output test2

    }

And you can run it here [1]


  [1]: http://play.golang.org/p/TwNPiRelIT

</details>



# 答案2
**得分**: 7

假设你知道指针和值之间的一般区别:

第一种方式是分配一个结构体,并将指向该分配的结构体的指针赋给变量 `p1`。

	p1 := &StructName{}

第二种方式是分配一个结构体,并将值(即结构体本身)赋给变量 `s`。
然后可以将指向该结构体的指针赋给另一个变量(在下面的示例中为 `p2`)。

	s := StructName{}
	p2 := &s

<details>
<summary>英文:</summary>

**Assuming you know the general difference between a pointer and a value:**

The first way allocates a struct and assigns a pointer to that allocated struct to the variable `p1`.

	p1 := &amp;StructName{}

The second way allocates a struct and assigns a value (the struct itself) to the variable `s`.
Then a pointer to that struct may be assigned to another variable (`p2` in the following example).

	s := StructName{}
	p2 := &amp;s


</details>



huangapple
  • 本文由 发表于 2015年11月8日 19:42:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/33593545.html
匿名

发表评论

匿名网友

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

确定