如何在结构类型上调用Go方法?

Ara*_*ram 1 go

not enough arguments in call to method expression AccountService.Open运行以下操作时收到错误.在这里运行:https://play.golang.org/p/Z9y-QIcwNy

type AccountService interface {
    Open(no string, name string, openingDate time.Time) AccountService
}

type Account struct {
    Num      string
    Name     string
    OpenDate time.Time
    Balance  float64
}

type SavingsAccount struct {
    InterestRate float32
    Account
}

type CheckingAccount struct {
    TransactionFee float32
    Account
}

func (a SavingsAccount) Open(no string, name string, openingDate time.Time) AccountService {
    return SavingsAccount{
        Account: Account{Num: no,
            Name:     name,
            OpenDate: openingDate,
        },
        InterestRate: 0.9,
    }
}
func (a CheckingAccount) Open(no string, name string, openingDate time.Time) AccountService {
    return CheckingAccount{
        Account: Account{Num: no,
            Name:     name,
            OpenDate: openingDate,
        },
        TransactionFee: 0.15,
    }
}

func main() {
    aliceAcct := AccountService.Open("12345", "Alice", time.Date(1999, time.January, 03, 0, 0, 0, 0, time.UTC))

    fmt.Println("Alice's account =", aliceAcct)
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 6

方法表达式 的结果AccountService.Open是带有类型的函数func(AccountService, string, string, time.Time) AccountService.代码缺少第一个参数.你可以这样称呼它:

aliceAcct := AccountService.Open(CheckingAccount{}, "12345", "Alice", time.Date(1999, time.January, 03, 0, 0, 0, 0, time.UTC))
Run Code Online (Sandbox Code Playgroud)

操场的例子

如果您没有有意义的值用作接收器,则使用函数代替:

func OpenCheckingAccount(no string, name string, openingDate time.Time) AccountService {
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果需要抽象帐户创建,则将服务定义为函数:

 type AccountService func(no string, name string, openingDate time.Time) AccountType
 func OpenSavings(no string, name string, openingDate time.Time) AccountType { ... }
 func OpenChecking(no string, name string, openingDate time.Time) AccountType { ... }
Run Code Online (Sandbox Code Playgroud)

OpenSavingsOpenChecking功能可作为一个AccountService上.

您将需要为服务和帐户使用不同的类型.在这里,我使用AccountService和AccountType.AccountType不是一个很好的名称,但已经使用了Account.AccountType可能定义如下:

type AccountType interface {
   func Deposit(int)
   func Withdraw(int)
}
Run Code Online (Sandbox Code Playgroud)