Golang中的加权随机数

时间:2016-09-17 21:37:25

标签: go

我必须在Golang中做加权随机,但我收到一个错误:

multiple-value randutil.WeightedChoice() in single-value context

代码:

package main

import "fmt"
import "github.com/jmcvetta/randutil"

func main() {    
    choices := make([]randutil.Choice, 0, 2)    
    choices = append(choices, randutil.Choice{1, "dg"})
    choices = append(choices, randutil.Choice{2, "n"})    
    result := randutil.WeightedChoice(choices)    
    fmt.Println(choices)
}

任何帮助都将深受赞赏。

2 个答案:

答案 0 :(得分:3)

func WeightedChoice(choices []Choice) (Choice, error)
返回Choice, error,因此请使用result, err := randutil.WeightedChoice(choices),例如此工作代码:

package main

import (
    "fmt"

    "github.com/jmcvetta/randutil"
)

func main() {
    choices := make([]randutil.Choice, 0, 2)
    choices = append(choices, randutil.Choice{1, "dg"})
    choices = append(choices, randutil.Choice{2, "n"})
    fmt.Println(choices) // [{1 dg} {2 n}]

    result, err := randutil.WeightedChoice(choices)
    if err != nil {
        panic(err)
    }

    fmt.Println(result) //{2 n}
}

输出:

[{1 dg} {2 n}]
{2 n}

答案 1 :(得分:1)

WeightedChoice会返回您在代码中未确认的错误。