4. Complex Types
Activity 4.01: Filling an Array
Solution:
- Create a new folder and add a file named
main.go
to it. - In
main.go
, add the package and imports:package main import "fmt"
- Create a function that returns an array:
func getArr() [10]int {
- Define an array variable:
var arr [10]int
- Use a
for i
loop to operate on each element of the array:for i := 0; i < 10; i++ {
- Use
i
, plus a bit of math, to set the correct value:arr[i] = i + 1 }
- Return the array variable and close the function:
return arr }
- In the
main()
function, call the function and print the returned value to the console:func main() { fmt.Println(getArr()) }
- Save the file. Then, in the folder you created in step 1, run the code using the following command:
go run .
Running the preceding code will produce the following output:
[1 2 3 4 5 6 7 8 9 10]