首页 > 解决方案 > 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")

  1. 什么时候不行
// 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")

标签: go

解决方案


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

推荐阅读