dongxian6715 2018-08-22 20:36
浏览 391
已采纳

GoLang字符串为空

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(): []
  • 写回答

1条回答 默认 最新

  • douganbi7686 2018-08-22 20:42
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器