6

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?

2 Answers 2

12

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
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

I would not use append() here; the length of the array is known and we can just allocate it.
Array size is know iff failed float parsing should 'abort' loop... I really don't like that you have changed the meaning of my code with your edit :/
Please undo my edit if you do not like it. It's okay.
Thank you very much. 1. for iterates over a slice is really simple yet useful. I guess this is the counterpart of map in a functional language. 2. strconv.ParseFloat not only convert the string to float, it also handles the separators - a mix use of comma and space, even irrelevant chars - strconv just done right. It's amazing! Go is simple and powerful.
2

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.