代码之家  ›  专栏  ›  技术社区  ›  Adam Smith

接口的同义结构字段和方法名称

go
  •  2
  • Adam Smith  · 技术社区  · 7 年前

    我正在构建一个表示网络上某些设备的类型结构。这些设备有很多类型,例如:

    type Foo struct  { ... }
    type Bar struct  { ... }
    type Spam struct { ... }
    

    但它们都有一些共同的领域,其中之一是 IP . 我想定义一下 Device 作为一个接口,我可以将它们逻辑地分组在一起

    type Device interface {
        IP() string
        ...
    }
    
    type LogicalGrouping struct {
        Devices []Device
        ...
    }
    

    但是我遇到了一个名字重叠的错误。

    func (f *Foo) IP() string { return f.IP }  // same method name as field name
    

    我可以重命名字段或方法,或者两者都重命名,但这肯定是一个常见的用例——按它们共同拥有的字段对结构进行分组?这里有惯用的解决方案吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Zak    7 年前

    IP struct IP()

    ip struct.IP struct.IP()

    foo bar spam

    type Foo struct {
        IP string
        A string 
        B string
    }
    
    type Bar struct {
        IP string
        A string 
        B string
    }
    
    type Spam struct {
        IP string
        A string 
        B string
    }
    

    type Inner struct {
        IP string
        A string 
        B string
    }
    
    type Foo struct {
        Inner
    }
    
    type Bar struct {
        Inner
    }
    
    type Spam struct {
        Inner
    }
    

    Inner struct.Inner

        2
  •  1
  •   cn007b Dheerendra Kulkarni    7 年前

    ip GetIP SetIP IP doc )-它清晰、简洁、简单。