登录
首页 >  Golang >  Go问答

关于Golang中使用结构体在方法之间传递变量的问题

来源:stackoverflow

时间:2024-02-27 19:48:19 452浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《关于Golang中使用结构体在方法之间传递变量的问题》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我有一个关于 go lang 程序的问题。在本练习中,我尝试将最初 20,000 美元的可变余额传递到存款方法,添加 3,000,然后传递到取款方法,减去 2,500。但最终余额仍然是20000。我不知道如何将一种方法中的变量传递给另一种方法,所以我可以获得最终的余额,应该是 20,500 美元。请帮忙!提前非常感谢您。

package main

import (
    "fmt"
    "time"
)

type Account struct {
    id int 
    balance float64
    annual_interest_rate float64
}

func (account Account) deposit(deposit1 float64) {
    account.balance = account.balance - deposit1

}

func (account Account) withdraw(withdraw1 float64) {
    account.balance = account.balance - withdraw1
}

func (account Account) getBalance() float64 {

    return account.balance
}

func (account Account) getMonthlyInterest() float64 {

    var monthlyInterestRate = account.annual_interest_rate / 1200
    var monthly_interest = account.balance * monthlyInterestRate

    return monthly_interest
}

func (account Account) getDateCreated() string {

    var output string = ""

    currentTime := time.Now()

    output = currentTime.Format("Monday January,01 2006 15:04:15 PM")

    return output
}
func main() {

    var account = Account {id:1122, balance:20000, annual_interest_rate:4.5}

    account.deposit(3000)
    account.withdraw(2500)

    fmt.Printf("Balance: $%.2f\n", account.getBalance())
    fmt.Printf("Monthly Interest: $%.2f\n", account.getMonthlyInterest())
    fmt.Printf("Date Created: %s\n", account.getDateCreated())
}

正确答案


方法会传递接收者的副本。因此,如果您使用 account,它们将使用 account 的副本(并且当它们返回原始内容时,原始内容没有更改);你可以通过使用指针来解决这个问题。 tour of go 很好地涵盖了这个问题,其中指出:

所以对代码的更改非常简单,例如

func (account *Account) deposit(deposit1 float64) {
    account.balance = account.balance - deposit1

}

有关所有功能均已更改的示例,请参阅 playground

理论要掌握,实操不能落!以上关于《关于Golang中使用结构体在方法之间传递变量的问题》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>