gpt4 book ai didi

go - Golang 中的加权随机数

转载 作者:IT王子 更新时间:2023-10-29 02:27:39 29 4
gpt4 key购买 nike

我必须在 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)
}

我们将不胜感激任何帮助。

最佳答案

func WeightedChoice(choices []Choice)(选择,错误)
返回 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}

关于go - Golang 中的加权随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551985/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com