Go 数组中可以有方法吗?
我正在学习Go并找到以下代码:Go 数组中可以有方法吗?,go,Go,我正在学习Go并找到以下代码: // newTestBlockChain creates a blockchain without validation. func newTestBlockChain(fake bool) *BlockChain { db, _ := ethdb.NewMemDatabase() gspec := &Genesis{ Config: params.TestChainConfig,
// 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
}
我的问题是:
gspec
变量被创建为两个值的关联数组,键为“Config”和键为“难度”,这很清楚
但我看到了这句话:
gspec.MustCommit(db)
我不明白,“MustCommit()”函数在哪里声明的?另外,Go中的数组是否有方法?奇怪的东西。在我对软件开发的理解中,只有类可以有方法,在这里,我看到了一个具有函数(方法)的数组。这个代码是怎么回事?你的假设是错误的
gspec
不是关联数组,而是Genesis
类型的对象。Genesis
类型可能是某种具有各种属性和方法的struct
-类型
有关结构和方法的示例,您可以访问以下页面:
Genesis
是一个struct
gspec
是指向struct
的指针。struct
不是关联数组。在Go中,map
是一个关联数组
你有:
gspec := &Genesis{
Config: params.TestChainConfig,
Difficulty: big.NewInt(1),
}
在哪里
复合文字为结构、数组、切片和 映射并在每次求值时创建新值。它们包括 文本的类型,后跟大括号绑定的元素列表。 每个元素前面可以选择相应的键 获取复合文字的地址将生成指向 使用文本值初始化的唯一变量
gspec
是使用Go复合文本构建的
方法是带有接收器的函数。方法声明绑定 标识符(方法名称)与方法关联,并将该方法关联 与接收器的基本类型 接收器是通过前面的额外参数部分指定的 方法名。该参数部分必须声明一个非变量 参数,接收器。其类型必须为T或*T形式 (可能使用括号),其中T是类型名。表示的类型 由T称为接收机基型;它不能是指针或指针 接口类型,并且必须在与 方法 一种形式为T或*T的类型(可能使用括号),其中T是一个类型名。可能有办法;它不能是指针或接口类型。Go数组类型可能有方法。Go map(关联数组)类型可能有方法。Go结构类型可能有方法 围棋没有课
参考资料:
@AdamSmith:您的示例是一个切片,它与数组不同。和。请参阅。每种类型都可以在go中有方法,甚至函数。是的,你可以在一个方法上声明一个方法。@MiloChristiansen:“每种类型都可以在go中有方法。”不是每种类型。“它不能是指针或接口类型,而且必须与方法定义在同一个包中。这是真的。接口上的方法有点荒谬,指针类型也没有它们是有原因的,我只是记不起它是什么……哦,好吧,如果我真的想知道的话,我会再次查找它:P。但对于所有的pr实际上,如果您想向类型添加方法,您可能可以。“只有类可以有方法”——Go没有类。
// 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"`
}
gspec := &Genesis{
Config: params.TestChainConfig,
Difficulty: big.NewInt(1),
}