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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真