在GO中通过JSON文件导入数据不符合预期- fmt.Println仅将隐藏的输出返回到提示符

ryevplcw  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(90)
package main

import (
    "flag"
    "fmt"

    "github.com/peterbourgon/ff"
)

var (
    compartmentOCID,
    bucketName,
    namespace *string
)

func main() {
    // Load config from JSON file
    compartmentOCID, bucketName, namespace := loadConfig()

    fmt.Println("Compartment OCID:", compartmentOCID)
    fmt.Println("Object Storage bucket name:", bucketName)
    fmt.Println("Object Storage namespace:", namespace)
}

// Load config
func loadConfig() (compartmentOCID *string, bucketName *string, namespace *string) {

    // Load creds from JSON into vars
    fs := flag.NewFlagSet("config", flag.ExitOnError)

    compartmentOCID = fs.String("compartment-ocid", "", "Compartment OCID")
    bucketName = fs.String("bucket", "", "Object Storage bucket name")
    namespace = fs.String("namespace", "", "Object Storage namespace")

    //  consumerKey = fs.String("consumerKey", "", "Twitter Consumer API key")
    //  consumerSecret = fs.String("consumerSecret", "", "Twitter Consumer API secret")

    //  accessToken = fs.String("accessToken", "", "Twitter Access Token")
    //  accessTokenSecret = fs.String("accessTokenSecret", "", "Twitter Access Token Secret")

    // senderEmail = fs.String("senderEmail", "", "Sender email")
    // recipientEmail = fs.String("recipientEmail", "", "Recipient email")

    //  ff.Parse(fs, nil, ff.WithConfigFile("config.json"), ff.WithConfigFileParser(ff.JSONParser))

    ff.Parse(fs, []string{},
        ff.WithConfigFile("config.json"),
        ff.WithConfigFileParser(ff.JSONParser))

    return compartmentOCID, bucketName, namespace
}

我是新来的,玩了一会儿。不知道我可能会错过什么,但我只收到以下输出:
共混物:0x1400008e040
对象存储桶名称:0x1400008e050
对象存储命名空间:0x1400008e060
这就是JSON中的内容:
“bucket”:“twitter-to-email”,
“compartment-ocid”:“oc1.tenancy.oc1..aaaaaa4gmjp4otjth423bk5aqnynhbhvpdok3a5ka4dtmcgytsciqsw3xq”,
“名称空间”:“frvhi6pjrbat”,

ghg1uchk

ghg1uchk1#

函数loadConfig返回指向字符串的指针。指针被打印为内存地址。
要获得预期的结果,请将函数更改为返回字符串。

func loadConfig() (compartmentOCID string, bucketName string, namespace string) {
   ... other code as is
   return *compartmentOCID, *bucketName, *namespace
}

这些变化是:

  • 将返回类型从*string更改为string
  • 在return语句中取消引用字符串指针。

程序不使用包级变量compartmentOCID、bucketName和namespace。通过删除变量的声明来减少混淆:

var (
    compartmentOCID,
    bucketName,
    namespace *string
)

相关问题