doutan4831 2017-05-30 08:55
浏览 23
已采纳

担忧与可用性的分离

I have always struggled keeping go modules neatly separated and avoiding cyclic dependencies.

Right now I have code like this:

    package chain


type Block struct{
    Content []byte
    Number int
}

var Chain []Block = make([]Block, 10)

func AddBlockToChain(block Block){
    // do some checks
    //...
    // add to chain
    Chain[block.Number] = block
}

func GetBlock(number int) Block {
    // do some checks
    //  ...
    // get from chain
    return Chain[number]
}

To achieve consensus I need some extra info on the block. The info may be different depending on which consensus algorithm I use. I want the consensus algorithm to be interchangeable (e.g. by flag on start up).

It would be convenient to store the info as fields in the block, so that when I call GetBlock(3) or get a block from anywhere else I can not only access the block but also the info on what state of consensus this block is in at the moment.

On the other hand I wanted to keep data that is only relevant for a certain consensus algorithm separate from basic block data - maybe even in a separate package.

How should I design my program? Where should I keep data relevant for a certain consensus algorithm?

Some background info:

I am trying to build a block chain application from scratch. I have a "chain" module responsible for storing blocks of data and a "consensus" module responsible for creating consensus between multiple peers running an instance of my program on what that data is.

  • 写回答

2条回答 默认 最新

  • douxing1969 2017-05-30 09:08
    关注

    consensus.Block and chain.Block are two separate types but since you are embeddding chain.Block in consensus.Block, you can access one from another.

    Just pass consensus.Block in AddBlockToChain():

    `func AddBlockToChain(block consensus.Block)`
    

    and then access it by: block.Block

    Example:

    package main
    
    import "fmt"
    
    type ChainBlock struct {
        id int
    }
    
    type ConsensusBlock struct {
        ChainBlock
        idCons int
    }
    
    func printChainBlockId(consBlock ConsensusBlock) {
        fmt.Println(consBlock.ChainBlock.id)
    }
    
    func main() {
        test := ConsensusBlock{
            ChainBlock: ChainBlock{
                id: 42,
            },
            idCons: 44,
        }
    
        printChainBlockId(admin)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)