具有多个签名的功能的实施[关闭]

问题描述 投票:-4回答:2

我有两个结构

type A struct {
    a'   A' // Another struct
    i    int
}

type B struct {
    b'   B' // Another struct
    i    int
}

有一个绑定到A的功能

func (a A) doSomething() {
    // code that is very similar to both structs A and B
}

Q。有没有一种方法可以实现与下面完全一样的功能?

func (a A, b B) doSomething() {
    // do something
}
function go methods overloading
2个回答
0
投票

取决于您要使用doSomething()功能执行的操作。

首先,您可以使用结构继承:

type Base struct {
    i int
}

type A struct {
    Base
    a string
}

type B struct {
    Base
    b string
}

func (b Base) doSomething() {
    fmt.Println("i:", b.i)
}

func (a A) doSomething() {
    fmt.Println("a.a:", a.a)
    a.Base.doSomething()
}

如果这不是您所需要的,也许您可​​以使用类型转换:

type A struct {
    a string
    i int
}

type B struct {
    b string
    i int
}

func doSomething(aOrB interface{}) {
    switch t := aOrB.(type) {
    case A:
        fmt.Println("a:", t.a, "i:", t.i)
    case B:
        fmt.Println("b:", t.b, "i:", t.i)
    default:
        panic("doSomething accepts A or B types only")
    }
}

-1
投票

您的意思是这样的吗?

package main

import "fmt"

type B struct {
    b string
}
type A struct {
    b string
}

func (b B) dosomething(a A) {
    fmt.Println(a)
    fmt.Println(b)
}

func main() {
    a := A{"A"}
    b := B{"B"}
    b.dosomething(a)
}
© www.soinside.com 2019 - 2024. All rights reserved.