dpruwm6206 2017-09-22 05:20
浏览 36
已采纳

数组在Go中可以有方法吗?

I am learning Go and found this code:

// newTestBlockChain creates a blockchain without validation.
func newTestBlockChain(fake bool) *BlockChain {
        db, _ := ethdb.NewMemDatabase()
        gspec := &Genesis{
                Config:     params.TestChainConfig,
                Difficulty: big.NewInt(1),
        }
        gspec.MustCommit(db)
        engine := ethash.NewFullFaker()
        if !fake {
                engine = ethash.NewTester()
        }
        blockchain, err := NewBlockChain(db, gspec.Config, engine, vm.Config{})
        if err != nil {
                panic(err)
        }
    blockchain.SetValidator(bproc{})
        return blockchain
}

My question is:

gspec variable is created as an associative array of 2 values with key 'Config' and key 'Difficulty', that's clear.

But then I see this line:

gspec.MustCommit(db)

and I don't understand, where was the 'MustCommit()' function declared? Also, does an array in Go have methods? Weird stuff. Only class can have methods in my understanding of software development and here, I am seeing an array that has functions (methods). What is up with this code?

  • 写回答

2条回答 默认 最新

  • dsg24156 2017-09-22 06:21
    关注

    gspec variable is created as an associative array of 2 values with key 'Config' and key 'Difficulty' , that's clear.

    It is not clear. It is false. Genesis is a struct. gspec is a pointer to a struct. A struct is not an associative array. In Go, a map is an associative array.

    You have:

    gspec := &Genesis{
        Config:     params.TestChainConfig,
        Difficulty: big.NewInt(1),
    }
    

    Where

    // Genesis specifies the header fields, state of a genesis block. It also defines hard
    // fork switch-over blocks through the chain configuration.
    type Genesis struct {
        Config     *params.ChainConfig `json:"config"`
        Nonce      uint64              `json:"nonce"`
        Timestamp  uint64              `json:"timestamp"`
        ExtraData  []byte              `json:"extraData"`
        GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
        Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
        Mixhash    common.Hash         `json:"mixHash"`
        Coinbase   common.Address      `json:"coinbase"`
        Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`
    
        // These fields are used for consensus tests. Please don't use them
        // in actual genesis blocks.
        Number     uint64      `json:"number"`
        GasUsed    uint64      `json:"gasUsed"`
        ParentHash common.Hash `json:"parentHash"`
    }
    

    https://godoc.org/github.com/ethereum/go-ethereum/core#Genesis


    Composite literals

    Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

    Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

    gspec := &Genesis{
        Config:     params.TestChainConfig,
        Difficulty: big.NewInt(1),
    }
    

    gspec is constructed using a Go composite literal.


    Method declarations

    A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.

    The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be of the form T or *T (possibly using parentheses) where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be defined in the same package as the method.

    A type of the form T or *T (possibly using parentheses), where T is a type name. may have methods; it must not be a pointer or interface type. A Go array type may have methods. A Go map (associative array) type may have methods. A Go struct type may have methods.

    Go does not have classes.


    References:

    The Go Programming Language Specification

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式