2016-09-17 218 views
-1

我必须做的加权随机在Golang但我得到一个错误:加权随机在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) 
} 

任何帮助将十分赞赏。

回答

1

WeightedChoice返回一个你在代码中没有确认的错误。

+0

我是有点新的去。在理解数据类型时遇到问题... – digiadit

+0

@digiadit要记住的重要事情是您必须确认所有返回的变量,如果您不想使用变量,则可以使用“_”来代替变量名称。通常,从不避免错误是很重要的。 –

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}