-2

I am new in go.I am taking the array as a input . Iam trying to append the integer value in the array

package main

import "fmt"

func main() {
    input := []int{1, 2}
    fmt.Println("input:", input)
    addnumber(input)
    fmt.Println("output:", input)
}

func addnumber(input []int) {
    input = append (input,3)
}
  • 3
    The builtin `append()` **returns** the new slice, for a reason, yet your `addNumber()` does not. Your `addNumber()` only assigns the new slice to the local `input` slice. Return the new slice and assign it to the `input` variable in `main()`. – icza Apr 27 '21 at 08:21
  • 2
    That is not an _array_, it is a _slice_ – Inian Apr 27 '21 at 08:22
  • Duplicate, this is a common issue for newcommers. Your function changes the _local_ variable `input` and nothing promotes this change back to the caller. – Volker Apr 27 '21 at 08:49
  • Does this answer your question? [Golang append an item to a slice](https://stackoverflow.com/questions/20195296/golang-append-an-item-to-a-slice) – advay rajhansa Apr 27 '21 at 16:55

2 Answers2

0

As described in the comments. You have to do something with the value inside the addnumber function. I changed it so that the new slice is being returned.

package main

import "fmt"

func main() {
    input := []int{1, 2}
    fmt.Println("input:", input)
    input = addnumber(input)
    fmt.Println("output:", input)
}

func addnumber(input []int) []int {
    return append (input,3)
}
Tom
  • 4,070
  • 4
  • 22
  • 50
-2
We have 2 options to achieve this
1)you can pass the address of the slice 
2)you can add return for that array in the addNumber function

https://play.golang.org/p/TB_UrH9t_Rz

package main

import "fmt"

func main() {
    input := []int{1, 2}
    fmt.Println("input:", input)
    addnumber(&input)
    fmt.Println("output:", input)
}

func addnumber(input *[]int) {
    *input = append (*input,3)
}