访问变量,其中包含在包中其他函数的一个函数中定义的键值

问题描述 投票:-5回答:1

我有一个文件名one.go如下,

one.go:

package main

import (
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {

    keys, ok := r.URL.Query()["key"]

    if !ok || len(keys) < 1 {
        log.Println("Url Param 'key' is missing")
        return
    }
    key := keys[0]

    log.Println("Url Param 'key' is: " + string(key))
}

我需要在main.go程序中访问此变量“key”。请帮忙。

尝试在one.go中声明另一个变量var Test = key,然后在main.go中尝试访问它时得到错误“undefined Test”

variables go scope global-variables
1个回答
-1
投票

要获取价值,您需要在main.go中导入one.go变量。在one.go中声明一个struct并将你的键赋给struct变量,然后在main.go中调用该struct。例如: -

package one

import (
    "log"
    "net/http"
)

type Value struct{
  key string
}

func handler(w http.ResponseWriter, r *http.Request) {

    keys, ok := r.URL.Query()["key"]

    if !ok || len(keys) < 1 {
        log.Println("Url Param 'key' is missing")
        return
    }
}

func GetValue() *Value {
    key := &Value{
        "keyvalue",
    }
    return key
}

您可以使用one.Value通过从函数返回或将值赋给结构然后在主文件中调用结构来访问该变量

package main

import (
    "log"

    "github.com/project/new/one"
)

func main() {
    // log.Println(one.Key)
    store := one.GetValue()
    log.Println(store)
}
© www.soinside.com 2019 - 2024. All rights reserved.