给新手的建议

我今天开始学习Go.特别是,我一直在阅读文档,
http://blog.go-lang.org
http://golang-book.com.

学习语言比练习语言更好的方法是什么?我在Go中编写了一个小程序,它使用最少数量的硬币对客户进行更改.阅读了早期的指南后,似乎有很多方法可以在Go中做同样的事情.

例如:

>在单个var语句中声明多个变量是否可以?
>你应该使用var声明变量,还是使用:= okay推断类型?
>在声明一片硬币时,最好在函数中本地声明这些吗?

package main

import "fmt"

func main() {
    fmt.Printf("%v", change(158))
}

func change(value int) []int {
    var (
        change []int
        coins = []int{ 100, 50, 20, 10, 5, 2, 1 }
    )

    for value > 0 {
        for i := 0; i < len(coins); i++ {
            if coins[i] <= value {
                change = append(change, coins[i])
                value -= coins[i]
                break
            }
        }
    }

    return change
}

非常感谢!

最佳答案 有些事情只是风格问题.另外,考虑如果要求您扩展功能会发生什么,例如,支持多种货币作为货币包的一部分.例如,我会将您的更改函数写为货币的方法:

package main

import "fmt"

type Currency struct {
    Name  string
    Notes []int
    Coins []int
}

var ukCurrency = Currency{
    Name:  "UK Sterling",
    Notes: []int{5000, 2000, 1000, 500},
    Coins: []int{100, 50, 20, 10, 5, 2, 1},
}

var usCurrency = Currency{
    Name:  "US Dollar",
    Notes: []int{10000, 5000, 2000, 1000, 500, 100},
    Coins: []int{25, 10, 5, 1},
}

func (c *Currency) Change(amount int) []int {
    var change []int
    for _, note := range c.Notes {
        for note <= amount {
            change = append(change, note)
            amount -= note
        }
        if amount == 0 {
            break
        }
    }
    for _, coin := range c.Coins {
        for coin <= amount {
            change = append(change, coin)
            amount -= coin
        }
        if amount == 0 {
            break
        }
    }
    return change
}

func main() {
    for _, currency := range []Currency{ukCurrency, usCurrency} {
        fmt.Println(currency.Name, currency.Change(158))
        fmt.Println(currency.Name, currency.Change(4747))
    }
}

输出:

UK Sterling [100 50 5 2 1]
UK Sterling [2000 2000 500 100 100 20 20 5 2]
US Dollar [100 25 25 5 1 1 1]
US Dollar [2000 2000 500 100 100 25 10 10 1 1]

作为一种风格问题,我会将您的更改功能修改为:

package main

import "fmt"

var coins = []int{100, 50, 20, 10, 5, 2, 1}

func change(amount int) []int {
    var change []int
    for _, coin := range coins {
        for coin <= amount {
            change = append(change, coin)
            amount -= coin
        }
        if amount == 0 {
            break
        }
    }
    return change
}

func main() {
    fmt.Println(change(158))
}
点赞