-3

Following is my code;

I am passing Field and Values to a method called insert(), where the values are populated in the string array Fields[] and Values[] respectively. The string array variables Fields[] and Values[] are getting populated in the insert() . But when I print the same in the main method, they are empty. I want the values to be retained.

How do I achieve this? Kindly let me know.

Thanks

Code:

package main

import (
    "fmt"
    "strings"
    "strconv"
)

var Field string = "text,text,text,text"
var Value string = "1,2,3,4"
var num int = 4
var Fields[]  string
var Values[]  string


func main() {

    insert(Field, Value)


    fmt.Println("Fields from main():", Fields)
    fmt.Println("Values from main():", Values)



}

func insert(Field string, Value string){
    if Field != "" && Value != "" {
        c := 0
                Fields := make([]string, num)
                Values := make([]string, num)

        field := strings.Split(Field, ",")
        value := strings.Split(Value, ",")

        for i := range field {
            Fields[c] = field[i]
            c = c + 1
                }
                c = 0
                for j := range value {
                        Values[c] = value[j]
            c = c + 1
                }

        fmt.Println("Fields from insert():", Fields)
        fmt.Println("Values from insert():", Values)

        }   
}

Following is the output;

Fields from insert(): [text text text text]
Values from insert(): [1 2 3 4]
Fields from main(): []
Values from main(): []
Dinu Kuruppu
  • 165
  • 1
  • 15
Sucheta
  • 11
  • 7
  • 1
    Possible duplicate of [Golang mixed assignation and declaration](https://stackoverflow.com/questions/37351022/golang-mixed-assignation-and-declaration) – Jonathan Hall Aug 23 '18 at 07:30

1 Answers1

0

In insert you have:

            Fields := make([]string, num)
            Values := make([]string, num)

This defines two new, local variables, which "shadow" the global variables. Remember, := defines and assigns a variable in one operation. To get the behavior you want, just assign to your globals instead of redefining them:

            Fields = make([]string, num)
            Values = make([]string, num)
Adrian
  • 42,911
  • 6
  • 107
  • 99