Go面试题25
1: 下面这段代码输出什么? 为什么?
func (i int) PrintInt() {
fmt.Println(i)
}
func main() {
var i int = 1
i.PrintInt()
}
- A.
1
- B.
compilation error
2: 下面这段代码输出什么? 为什么?
type People interface {
Speak(string) string
}
type Student struct {}
func (stu *Student) Speak(think string) (talk string) {
if think == "speak" {
talk = "speak"
} else {
talk = "hi"
}
return
}
func main() {
var peo People = Student{}
think := "speak"
fmt.Println(peo.Speak(think))
}
- A.
speak
- B.
compilation error
参考答案及解析
1: 答案及解析: B
. 基于类型创建的方法必须定义在同一个包内,上面的代码基于int
类型创建了PrintInt()
方法, 由于int
类型和方法PrintInt()
定义在不同的包内,所有编译错误.解决的方法可以定义一种新的类型:
type Myint int
func (i Myint) PrintInt() {
fmt.Println(i)
}
func main() {
var i Myint = 1
i.PrintInt()
}
2: 答案及解析: B
.编译错误: Student does not implement People (Speak method has pointer receiver)
, 值类型Student
没有实现接口的Speak()
方法,而是指针类型*Student
实现了该方法.解决方式如下:
type People interface {
Speak(string) string
}
type Student struct {}
func (stu *Student) Speak(think string) (talk string) {
if think == "speak" {
talk = "speak"
} else {
talk = "hi"
}
return
}
func main() {
var peo People = &Student{}
think := "speak"
fmt.Println(peo.Speak(think))
}
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付