Golang:返回指针和解引用

huangapple go评论80阅读模式
英文:

Golang: returning pointers and derefrencing

问题

所以我有一个名为getToken()的函数。

func getToken() jwt.MapClaims {
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkYW0iLCJwYXNzd29yZCI6InRlc3QiLCJpYXQiOjE0ODcyMDY2OTIsImV4cCI6MTUxODc2NDI5Mn0.6LQo_gRwXiFBvNIJOwtf9UuxoQMZZ3XNILTnU-46-Zg"
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
        }

        hmacSampleSecret := []byte("supersecretkittysecret")
        return hmacSampleSecret, nil
    })

    if err != nil {
        println("error")
    }

    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        return claims
    } else {
        return nil
    }
}

然后对应的调用:

res := getToken()

println(res["username"])

为什么res["username"]等于两个内存地址(0x2b3c20,0xc420075420)?它应该只是一个字符串,比如adam。我还尝试过func getToken() *jwt.MapClaimsreturn &claims,但这仍然没有帮助。

英文:

So I have a function getToken()

func getToken() jwt.MapClaims {
	tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkYW0iLCJwYXNzd29yZCI6InRlc3QiLCJpYXQiOjE0ODcyMDY2OTIsImV4cCI6MTUxODc2NDI5Mn0.6LQo_gRwXiFBvNIJOwtf9UuxoQMZZ3XNILTnU-46-Zg"
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		hmacSampleSecret := []byte("supersecretkittysecret")
		return hmacSampleSecret, nil
	})

	if err != nil {
		println("error")
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims
	} else {
		return nil
	}

}

Then the corresponding call:

res := getToken()

println(res["username"])

Why is res["username"] equal to two memory addresses (0x2b3c20,0xc420075420)? This should just be a string like adam. I have also tried func getToken() *jwt.MapClaims and return &claims, but this still did not help.

答案1

得分: 2

你应该尝试使用fmt.Println而不是println。下面是使用printlnfmt.Println打印地图的示例代码:

package main

import (
	"fmt"
)

func foo() map[string]string {
	return map[string]string{
		"k": "value",
	}
}

func main() {
	res := foo()
	println("Output from println:", res)          // 打印指针地址
	fmt.Println("Output from fmt.Println: ", res) // 打印地图
}

输出:

Output from println: 0x10432200
Output from fmt.Println:  map[k:value]

你可以在这里查看代码示例:https://play.golang.org/p/gCNqng3KEE

英文:

You should try using fmt.Println instead of println. Here's an example of printing a map using println vs fmt.Println

package main

import (
	"fmt"
)

func foo() map[string]string {
	return map[string]string{
		"k": "value",
	}
}

func main() {
	res := foo()
	println("Output from println:", res)          // prints pointer address
	fmt.Println("Output from fmt.Println: ", res) // prints the map
}

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

Output:

Output from println: 0x10432200
Output from fmt.Println:  map[k:value]

huangapple
  • 本文由 发表于 2017年2月16日 09:55:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42263426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定