登录
首页 >  Golang >  Go问答

结构类型中的条件/可选字段

来源:stackoverflow

时间:2024-03-30 14:00:33 284浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《结构类型中的条件/可选字段》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我有一个像这样的 node 结构类型:

package tree

// enum for node category
type level int32
const (
    leaf level = iota + 1
    branch
    root
)

type node struct {
    children []*node
    parent   *node
    x        float32
    y        float32
    z        float32
    dim      float32
    category level
    leafpenetration float32 // needed only if category is "leaf"
    rootpaddim float32      // needed only if category is "root"
}

我有两个 node 字段,它们是可选的,仅根据 category 字段需要:

    leafPenetration float32 // Needed only if category is "Leaf"
    rootPadDim float32      // Needed only if category is "Root"

当前的 node 实现正常吗?结构类型中此类可选/条件字段的最佳实践是什么?


解决方案


我最终使用了一种非常简化的方法:

package tree

// enum for node category
type level int32
const (
    leaf level = iota + 1
    branch
    root
)

type node struct {
    category level
    parent   *node
    x        float32
    y        float32
    z        float32
    dim      float32

    roott  float32 // root thickness
    rootd  float32 // root diameter
    rootbr float32 // root bezel ratio of top-bottom, i.e. top d is larger by this much
    leafp  float32 // leaf penetration
}

func newnode(cat level, parent *node, x, y, z, dim float32) *node {
    n := &node{
        category: cat,
        parent:   parent,
        x:        x,
        y:        y,
        z:        z,
        dim:      dim,
    }
    switch n.category {
    case leaf:
        n.leafp = float32(0.3)
    case root:
        n.roott = float32(2)
        n.rootd = float32(30)
        n.rootbr = float32(1.08)
    }
    return n
}

默认情况下,字段初始化为类型的零值——在 float32 的情况下,它是 0。为了避免这种情况,通常对可选字段使用指针,例如:

type Node struct {
    Children []*Node
    Parent   *Node
    X        float32
    Y        float32
    Z        float32
    Dim      float32
    Category Level

    // Optional fields
    LeafPenetration *float32  // Needed only if category is "Leaf"
    RootPadDim      *float32  // Needed only if category is "Root"
}

指针字段将默认为 nil

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>