go - Type a type后,不能再混用
问题描述
config.Config 有一个方法func String(string) string
,我想将这些方法与我的 Type Config
1混合使用。
// type Config struct
type Config struct {
// a struct has many methods
config.Config
Path string
}
// new and call string method
var a Config = &Config{}
a.String("test")
- 什么时候不行
// type Config struct
type (
Configure config.Config
Config struct {
Configure
Path string
}
)
// new and call string method
var a Config = &Config{}
// error, can not call `String()`
a.String("test")
解决方案
https://go101.org/article/type-system-overview.html说得很好:
类型定义中新定义的类型及其各自的源类型是两种不同的类型。
这有效:
package main
import(
"fmt"
)
type MyType struct {
Id int
}
func (mt *MyType)Method() {
fmt.Printf("Method called %d\n", mt.Id)
}
type MyOtherType MyType
func main(){
mt := &MyType{Id:3}
mt.Method()
//mt2 := &MyOtherType{Id:5}
//mt2.Method()
}
但是如果你取消注释mt2.Method()
,你会得到一个错误:
mt2.Method undefined (type *MyOtherType has no field or method Method)
组合的工作方式不同。结构确实获得了组成它的结构的方法:
package main
import (
"fmt"
)
type MyType struct {
Id int
}
func (mt *MyType) Method() {
fmt.Printf("Method called %d\n", mt.Id)
}
type MyOtherType struct {
MyType
}
func main() {
mt := &MyType{Id: 3}
mt.Method()
mt2 := &MyOtherType{MyType{Id: 5}}
mt2.Method()
}
这就是类型组合的魔力。
$ go run t.go
Method called 3
Method called 5
推荐阅读
- javascript - 如何解决鼠标悬停在图表上会出现旧数据/图表的问题?
- python - 训练准确率 100%,验证准确率不变
- hybris - 如何修改 Hybris Backoffice 重新聚焦功能
- python - 将列表列表与字典进行比较
- docker - 通过 API 调用为 DockerHub 存储库创建新的构建规则
- javascript - 如何按元素首字母过滤 JavaScript 数组?
- javascript - 将两个嵌套的 json 对象与 javascript 结合起来,并用一个键循环遍历它
- unity3d - 如何在 Cinemachine 中将游戏窗口指南中心更改为玩家中心?
- javascript - 如何让 JavaScript 画布覆盖整个屏幕?
- javascript - 带有授权标头的 HTTP 请求