I'm new to programming, and trying to write a simple average program in Go.
package main
import (
    "fmt"
    "os"
)
var numbers []float64
var sum float64 = 0
func main() {
    if len(os.Args) > 1 {
        numbers = os.Args[1:]
    }
    fmt.Println("Numbers are: ", numbers)
    for _, value := range numbers {
        sum += value
    }
}
http://play.golang.org/p/TWNltPO71N
when I build the program, I got this error:
prog.go:15: cannot use os.Args[1:] (type []string) as type []float64 in assignment
[process exited with non-zero status]
So how to convert a slice of string to a slice of float numbers? Can I map a convert function to the slice?
You need to convert string to float64 using strconv.ParseFloat function:
package main
import (
    "fmt"
    "os"
    "strconv"
)
var numbers []float64
var sum float64 = 0
func main() {
    if len(os.Args) <= 1 {
        return
    }
    for _, arg := range os.Args[1:] {
        if n, err := strconv.ParseFloat(arg, 64); err == nil {
            numbers = append(numbers, n)
        }
    }
    fmt.Println("Numbers are: ", numbers)
    for _, value := range numbers {
        sum += value
    }
}
                        It can't convert because string and int are not compatible.
Instead of having the numbers slice, just iterate over os.Args[1:], using ParseFloat from the strconv package.
fmt.Print("Numbers are: ")
for _, arg := range os.Args[1:] {
    fmt.Print(arg, " ")
    value, err := strconv.ParseFloat(arg, 64)
    if err != nil {
        panic(err)
    }
    sum += value
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With