Go每日一题 今日(2025-03-26) 的题目如下

4815 次点击 · 7 赞 ·大约8小时之前 开始浏览   · 来源「Golang修养之路」

以下代码能通过编译吗?为什么?

package main

import (
	"fmt"
)

type People interface {
	Speak(string) string
}

type Student struct{}

func (stu *Student) Speak(think string) (talk string) {
	if think == "love" {
		talk = "You are a good boy"
	} else {
		talk = "hi"
	}
	return
}

func main() {
	var peo People = Student{}
	think := "love"
	fmt.Println(peo.Speak(think))
}
4815 阅读
63 回复
hupeng
hupeng · #51 · 2年之前

mark

brothersam
brothersam · #52 · 2年之前

不能,是 *Student 指针实现了方法。

TimLiuDream
TimLiuDream · #53 · 2年之前

不能,是 *Student 指针实现了方法。

cllgeek
cllgeek · #54 · 2年之前

mark

BigBigGopher
BigBigGopher · #55 · 大约1年之前

mk

a406299736
a406299736 · #56 · 大约1年之前

1111111

BigBigGopher
BigBigGopher · #57 · 11月之前

发生多态的几个要素: 1、有interface接口,并且有接口定义的方法 2、有子类去重写interface的接口 3、有父类指针指向子类对象 本题中,是*student指针实现了方法

WangWangZhou
WangWangZhou · #58 · 11月之前

报错了.\main.go:23:19:

cannot use Student{} (value of type Student) as People value in variable declaration: Student does not implement People (method Speak has pointer receiver)
feiyang
feiyang · #59 · 7月之前

应该改成 var peo People = &Student{} 即可编译通过。(People 为 interface 类型,就是指针类型)

YuPeng
YuPeng · #60 · 4月之前

mark

AronVic
AronVic · #61 · 4月之前

func (stu Student) Speak(think string) (talk string) { if think == "love" { talk = "You are a good boy" } else { talk = "hi" } return }

这样也可以编译通过,输出也是:You are a good boy

zhangwei_go
zhangwei_go · #62 · 4月之前

所以应该改成 var peo People = &Student{} 即可编译通过。(People 为 interface 类型,就是指针类型)

euibieur894
euibieur894 · #63 · 4月之前

Student{} 已经重写了父类 People{} 中的 Speak(string) string 方法,那么只需要用父类指针指向子类对象即可。应该改成 var peo People = &Student{}

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传