Go-Structure

定义&赋值

要点:
- 定义一个新的结构体
- 结构体对象的声明与初始化
- 对象和指针

package main
import "fmt"

type Point struct {
    x float64 
    y float64 
}

/*
You could write the code as below, which is more convenient.
type Point struct {
    x,y float64
}
*/

func print(p Point) {
    fmt.Printf("Point[x=%.2f, y=%.2f]\n", p.x, p.y)
}

func main() {
    var p1 Point; // all fields are set to default value.

    print(p1)

    p1.x++
    p1.y++
    print(p1)

    p2 := new (Point) // p2 is a pointer, and all filed are set to default value.
    print(*p2)

    p3 := Point{x : 31, y : 32}
    print(p3)

    p4 := Point{41, 42}
    print(p4)

    p5 := &Point{51, 52} // a pointer
    //print(p5) //cannot use p5 (type *Point) as type Point in argument to print
    print(*p5)
}

从目前来看,这个struct和C/C++的struct是完全一样的。——Go的初始化倒是方便很多。

接下来是struct往class转换的关键点。

结构体嵌套&成员方法

注:会适当在一个例子中描述多个语法点,从而减少代码阅读量。

要点:
- 在Go中没有class这个语法或关键字,都统一为struct,但可以为struct定义成员函数,从而和传统的class概念保持一致了。
- 在area()这个函数声明中,func和函数名area之间的,Go称之为receiver。这个receiver也可以看做一种参数,有名称、有类型,在函数体中也可以直接引用。
- 尽管area声明的时候是*Circle,但Circle对象(非指针类型)仍然可以用.操作符访问。——Go会自动处理。

package main
import "fmt"
import "math"

type Point struct {
    x,y int
}

type Circle struct {
    center Point 
    r int
}

func (c *Circle) area() float64 {
    return math.Pi * float64(c.r) * float64(c.r)
}

func main() {
    var circle Circle
    circle.center.x = 3;
    circle.center.y = 4;
    circle.r = 5;

    fmt.Println(circle.area())
}

匿名数据成员

Go支持anonymous fields. 这种方式使用起来更为方便。

在Introducing Go中,论证了这种anonymous fields与has-a&is-a之间的辩论关系。用设计层面看,anonymous fields的确更像继承关系,即is-a。有传统的命名域(non-anonymous fields)属于一种依赖关系,即has-a。但有时候为了使用上的方便,特别是在Go语言提供了这么便利的语法下,anonymous fields还是很有诱惑力的,再加上Go倡导的简洁思想,为什么不用呢?!

package main
import "fmt"
import "math"

type Point struct {
    x,y int
}

type Circle struct {
    Point 
    r int
}

func (c *Circle) area() float64 {
    return math.Pi * float64(c.r) * float64(c.r)
}

func main() {
    var circle Circle
    circle.x = 3;
    circle.y = 4;
    circle.r = 5;

    fmt.Println(circle.area())
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值