请教golang如何实现其他文件中定义的接口

bwilling · 2017-11-08 08:37:36 · 4861 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-11-08 08:37:36 的主题,其中的信息可能已经有所发展或是发生改变。

比如 a.go:

package be

type Animail interface {
    Say()
    Run()
}

b.go:

package model

import (
    "fmt"
    )

type Dog struct {
}

type Cat struct {
}

func (dog Dog) Say(){
    fmt.Print("狗")
}

func (cat Cat) Say(){
    fmt.Println("猫")
}

b.go中的 Cat 该怎么实现a.go中定义的接口呢


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

4861 次点击  
加入收藏 微博
7 回复  |  直到 2020-01-08 18:35:08
abin
abin · #1 · 7年之前

Cat 有Say() 和 Run() 方法就可以了

bwilling
bwilling · #2 · 7年之前
abinabin #1 回复

Cat 有Say() 和 Run() 方法就可以了

就是我b.go这那么写的吗?但是并不对啊

var an be.Animail
an = new(model.Cat)

这段代码是报错的,提示:

Cannot use new(model.Cat) (type *model.Cat) as type be.Animail in assignment less... (⌘F1) 
Reports incompatible types in binary and unary expressions.
abin
abin · #3 · 7年之前
bwillingbwilling #2 回复

#1楼 @abin 就是我b.go这那么写的吗?但是并不对啊 ``` var an be.Animail an = new(model.Cat) ``` 这段代码是报错的,提示: ``` Cannot use new(model.Cat) (type *model.Cat) as type be.Animail in assignment less... (⌘F1) Reports incompatible types in binary and unary expressions. ```

Dog和Cat都没有实现Run方法

bwilling
bwilling · #4 · 7年之前

@abin 非常感谢~~~

johnsen
johnsen · #5 · 6年之前

493589546@qq.com,求资料!!!

cqcsdzmt
cqcsdzmt · #6 · 6年之前

type Animail interface { Say() Run() } 这句话可以不写哦! var d Dog d.Say()

bwilling
bwilling · #7 · 5年之前
cqcsdzmtcqcsdzmt #6 回复

type Animail interface { Say() Run() } 这句话可以不写哦! var d Dog d.Say()

不写?不声明接口 ,怎么知道 d 是实现的那个接口?

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