Nulik
Nulik

Reputation: 7360

Can array have methods in 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?

Upvotes: 0

Views: 147

Answers (2)

peterSO
peterSO

Reputation: 166569

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

Upvotes: 5

Dekker1
Dekker1

Reputation: 5786

Your assumption is wrong. gspec isn't an associative array, but a object of type Genesis. The Genesis type is probably some sort of struct-type with various attributes and methods.

For examples on structs and methods you could visit the following Go by Example pages:

Upvotes: 3

Related Questions