关于golang:GO的第二天学习结构体

14次阅读

共计 1484 个字符,预计需要花费 4 分钟才能阅读完成。

定义
 构造体是一种聚合的数据类型,由零个或多个任意类型的值聚合成的实体。
type Employee struct {
    ID int
    Name string
    Address string
    DoB time.time
    Position string
    Salary int
    ManagerId int
}    

var dilbert Employee

// 成员的赋值
dilbert.Salary -= 50900

postion := &dilbert.Position // 对成员取指针,而后通过指针拜访
*position = "Senior" + *position 

一个命名为 S 的构造体类型不能在蕴含 S 类型的成员:因为一个聚合的值不能蕴含它本身。(该限度同样适宜用于数据)然而 S 类型的构造体能够蕴含 * S 指针类型的成员,这个让咱们创立递归的数据结构,比方链表和树。

type tree struct {
    value int
    left,right *tree
}

func sort(values []int) {
    var root *tree
    for _,v :=range values {root = add(root,v)
    }
    appendValues(values[:0],root)
}

func appendValue(values []int,t *tree) []int {
    if t != nil {values = appendValues(values,t.left)
        values = append(values,t.value)\
        values = appendValues(values,t.right)
    }
    return values
}

func add(t *tree,value int) *tree {
    if t==nil {t = new(tree)
        t.value = value
        return t
    }
   
    if value < t.value {t.left = add(t.left,value)
    } else {t.right = add(t.right,value)
    }
    return t
}    
构造体字面值

构造体值也能够用构造体字面值示意,构造体字面值能够指定每个成员的值

type Point struct {X,Y int}
p := Point{1,2}

// 如果思考效率的话,较大的构造体通常会用指针的形式传入和返回

func Bonus(e *Employee,percent int)int {return e.Salary * percent / 100}    
创立构造体
pp := &Point{1,2}
// 也能够上面这种
pp := new(Point)
*pp = Point{1,2}
构造体嵌入和匿名成员
type Circle struct {X,Y,Radius int}

type Wheel struct {X,Y,Radius,Spokes int}

一个 Circle 代表的圆形类型蕴含了规范圆心的 X 和 Y 坐标信息,和一个 Radius 示意半径信息。一个 Wheel 轮型除了蕴含 Circle 类型所有的全副成员外,还减少了 Spokes 示意伸向辐条的数量。

var w Wheel
w.X = 8
w.Y = 8
w.Raduis = 5
w.Spokes = 20

随着库中几何形态的增多,咱们肯定会留神它们之间的类似和反复之处,所以咱们可能为了便于保护而将雷同的属性独立起来

type Point struct {X,Y int}

type Circle struct {
    Center Point
    Raduis int
}


type Wheel struct {
    Circle Circle
    Spokes int
}

var W Wheel
w.Circle.Center.Center.X = 8
w.Circle.Center.Center.Y = 8
w.Circle.Raduis = 8
W.Spokes = 20
正文完
 0