dsf6281 2015-04-09 01:03
浏览 25
已采纳

为什么在函数调用后我的字段被截断?

http://play.golang.org/p/xFBSZta2CL

I have been trying everything for 2 hours now. Going into the main function, we immediately get to line 24-26:

prompter.Define(&Field{"name"})
prompter.Define(&Field{"age"})

The define function:

fmt.Printf("fields: %+v
", c.fields)
c.fields = append(c.fields, f)
fmt.Printf("fields: %+v
", c.fields)

After the function call, the c.fields array is empty again!!! Output:

fields: []
fields: [0x1040a120]
fields: []
fields: [0x1040a130]
  • 写回答

1条回答 默认 最新

  • dongtun1872 2015-04-09 01:09
    关注

    The Go Programming Language

    Frequently Asked Questions (FAQ)

    Should I define methods on values or pointers?

    func (s *MyStruct) pointerMethod() { } // method on pointer
    func (s MyStruct)  valueMethod()   { } // method on value
    

    For programmers unaccustomed to pointers, the distinction between these two examples can be confusing, but the situation is actually very simple. When defining a method on a type, the receiver (s in the above examples) behaves exactly as if it were an argument to the method. Whether to define the receiver as a value or as a pointer is the same question, then, as whether a function argument should be a value or a pointer. There are several considerations.

    First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.) In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

    By the way, pointer receivers are identical to the situation in Java, although in Java the pointers are hidden under the covers; it's Go's value receivers that are unusual.

    Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

    Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

    For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.

    In Go, all arguments and return values are passed by value. Receivers are passed by value. Use a pointer receiver to change the value. For example,

    package main
    
    import (
        "fmt"
    )
    
    type Prompter interface {
        Define(f *Field)
    }
    
    type Field struct {
        Key string
    }
    
    type Provider interface {
        Prompt(Prompter)
    }
    
    var providers = []Provider{
        MyProvider{},
    }
    
    type MyProvider struct{}
    
    func (p MyProvider) Prompt(prompter Prompter) {
        prompter.Define(&Field{"name"})
        prompter.Define(&Field{"age"})
    }
    
    type CliPrompter struct {
        fields []*Field
    }
    
    func NewCliPrompter() *CliPrompter {
        return &CliPrompter{
            fields: make([]*Field, 0, 100),
        }
    }
    
    func (c *CliPrompter) Define(f *Field) {
        fmt.Printf("fields: %+v
    ", c.fields)
        c.fields = append(c.fields, f)
        fmt.Printf("fields: %+v
    ", c.fields)
    }
    
    func main() {
        providers[0].Prompt(NewCliPrompter())
    }
    

    Output:

    fields: []
    fields: [0x1040a120]
    fields: [0x1040a120]
    fields: [0x1040a120 0x1040a130]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。