ITPub博客

首页 > > > JAVA开发者的Golang快速指南-2

JAVA开发者的Golang快速指南-2

作者:zhmw 时间:2019-12-24 10:11:31 0 删除 编辑

类型继承

Golang在设计上未采用Java的“继承(extends)”,它的继承是通过组合来完成的。例如:

type Rectangle struct {

Shape

width int

height int

}

上面Rectangle结构中有一个类型为Shape的匿名成员。Shape中包含的所有字段和方法在Rectangle对象上都是可见的。但是需要注意的是,不像在Java中,可以将Rectangle传递给Shape为参数的函数,这在Go中是行不通的。要获得这种类型的多态性,应该使用Go接口。

 

多态性、接口

在Java中有特定的接口类型,这些接口类型定义了对象的行为。在Go中,也有类似的概念,可以通过intefaces来实现。例如,下面这个接口声明了一个具有Print()方法的Shape类型:

type Shape interface {

Print()

} 

当使用Go来创建结构时,不需要像在Java中那样用“implementation”来声明它。它是隐式的,只需要实现了该接口对应的方法,对应的结构体就可以被传递给需要的函数:

type Rectangle struct {

width int

height int

}

func (r *Rectangle) Print() {

fmt.println("Rectangle!");

}

此时,Rectangle对象可以传递给任何接收Shape类型的函数,因为它实现了该类型的所有方法。

 

For循环

Go中的For循环,样例如下:

for i := 1; i <= 10; i++ {

fmt.Println(i)

}

然而,当迭代一个数组(或类似于数组的东西,例如,字符串,映射,切片等),可以使用range运算符(假设foo是一个列表List):

for v := range foo {

fmt.println("value="+v);

}

如果在遍历列表时需要知道该列表的索引,则可以这样编写代码:

for i, v := range foo {

fmt.println("index " + i +"has value="+v);

}

 

While循环

Go中还可以像这样再次使用for循环:

sum := 1

for sum < 1000 {

sum += sum

}

fmt.Println(sum)

或者实现一个无限while循环:

for {

something...

}

 

指针和引用

Golang中需要显式地使用指针和引用,而Java通常隐藏这些。例如,Java中可以这样做:

Shape shape = new Shape();

shape.foo(); 

但是在Go中,必须直接处理指针:

type Rectangle struct {

width int

height int

}

func updateRectangle(r *Rectangle){

r.width = 5;

r.height = 10;

}

func main() {

r := Rectangle{20,30}

updateRectangle(&r)

}

当main函数执行完毕时,Rectangle对象中r.width=5,r.height=10。注意:必须显式地引用指针。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69901620/viewspace-3160066/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-12-04

  • 博文量
    295
  • 访问量
    9531