从函数设置结构域

时间:2019-03-12 14:03:14

标签: go

我敢肯定有更好的方法可以做到这一点,我知道这很简单,但是我是新手,所以请耐心等待。我试图通过两个函数(playersObjectsetCalculations)设置结构(Calculations)的字段,更具体地说,我传入两个数组({{1} }和playerData,从main到这些函数,并在这些函数中执行计算,并希望返回这些值,以便可以在结构中对其进行设置。

playerData2

我收到错误package main import ( "fmt" "os" "log" "strings" "bufio" "strconv" ) type playersObject struct { firstname, lastname string batting_average, slugging_percentage, OBP, teamaverage float64 } func strToFloat(playerData []string, playerData2 []float64) []float64 { for _, i := range playerData[2:] { j, err := strconv.ParseFloat(i, 64) if err != nil { panic(err) } playerData2 = append(playerData2, j) } return playerData2 } func (player *playersObject) setCalculations (playerData []string, playerData2 []float64) { player.firstname = playerData[1] player.lastname = playerData[0] player.batting_average = (playerData2[2] + playerData2[3] + playerData2[4] + playerData2[5]) / (playerData2[1]) player.slugging_percentage = ((playerData2[2]) + (playerData2[3]*2) + (playerData2[4]*3) + (playerData2[5]*4) )/(playerData2[1]) player.OBP = (( playerData2[2] + playerData2[3] + playerData2[4] + playerData2[5] +playerData2[6] +playerData2[7])/ (playerData2[0])) } func (player *playersObject) Calculations () (string, string, float64, float64, float64, ) { return player.firstname, player.lastname, player.batting_average, player.slugging_percentage, player.OBP } func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter file name: ") fileName, err := reader.ReadString('\n') if err != nil { log.Fatalf("failed opening file: %s", err) } fileName = strings.TrimSuffix(fileName, "\n") //fmt.Printf("%q\n", fileName) file, err := os.Open(fileName) scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) var fileOfPlayers []string for scanner.Scan() { fileOfPlayers = append(fileOfPlayers, scanner.Text()) } file.Close() // var total_Average_sum float64 = 0 var countofplayers float64 = 0 //var total_average float64 = 0 for _, player := range fileOfPlayers { countofplayers ++ playerData := strings.Split(player, " ") var playerData2 = []float64{} playerData2 = strToFloat(playerData, playerData2) player := playersObject{} player.setCalculations(playerData, playerData2) calcs := player.Calculations() fmt.Println(firstname, lastname, batting_average, slugging_percentage, OBP) } } multiple-value player.Calculations() in single-value contextand

我知道这是非常不正确的,但是我又是新手,请OOP。如果可以通过任何更简单的方式完成此操作,我都会接受并感谢所有帮助和提示。谢谢

1 个答案:

答案 0 :(得分:2)

在这里,由于Calculations()返回了多个值而引发了错误,但是您正在尝试将其分配给单个变量。

您需要更改player.Calculations()方法的调用

    calcs := player.Calculations()

firstname, lastname, batting_average, slugging_percentage, OBP := player.Calculations()

话虽如此,我建议您阅读有关here的golang的更多信息。您需要根据最佳实践重新编写代码