I try to write a small application in go that takes 'x' numbers of integers from standard input, calculates the mean and gives it back. I have only gotten so far:
func main() { var elems, mean int sum := 0 fmt.Print("Number of elements? ") fmt.Scan(&elems) var array = new([elems]int) for i := 0; i < elems; i++ { fmt.Printf("%d . Number? ", i+1) fmt.Scan(&array[i]) sum += array[i]; }............
When trying to compile this I get the following error message:
invalid array bound elems
What is wrong here?
Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary.
To get length of an array in Go, use builtin len() function. Call len() function and pass the array as argument. The function returns an integer representing the length of the array.
You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.
But arrays in Golang cannot be resized, hence we have slices, whose size can be dynamically changed. Slices have length and capacity. Length is the number of elements present in the slice.
You should use a slice instead of an array:
//var array = new([elems]int) - no, arrays are not dynamic var slice = make([]int,elems) // or slice := make([]int, elems)
See "go slices usage and internals".
Also you may want to consider using range for your loop:
// for i := 0; i < elems; i++ { - correct but less idiomatic for i, v := range slice {
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