别名转换

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

Alias conversions

问题

我有一个作为外部库一部分的struct AccessToken,我在自己的库中使用它。我想返回这种类型的值,但我不认为我的内部实现应该对外部可见。类型别名看起来很适合这个问题。

type AccessToken oauth.AccessToken

但是当我尝试下面的代码时,我遇到了一个错误:

func Auth(key string, secret string) *AccessToken {
    ...
    var token oauth.AccessToken = AuthorizeToken(...)
    return AccessToken(*token)
}

错误信息如下:

cannot use AccessToken(*accessToken) (type AccessToken) as type *AccessToken in return argument

很明显,我可以逐个字段地复制结构体。但是否有任何方法可以使用类型别名呢?

英文:

I have struct AccessToken as a part of external library and I use that library in my own. I'd like to return a value of this type but I do not see any reasons why my internal implementation should be visible from outside. Type alias looks great for this.

type AccessToken oauth.AccessToken

But I'm getting an error when trying to do next:

func Auth(key string, secret string) *AccessToken {
...
	var token oauth.AccessToken = AuthorizeToken(...)
	return AccessToken(*token)
}

Error:

cannot use AccessToken(*accessToken) (type AccessToken) as type *AccessToken in return argument

It's clear that I can just copy structures field by fiend. But is there any way to use aliases?

答案1

得分: 5

我不知道你遇到了什么错误,但是这个表达式是错误的:

func Auth(key string, secret string) *AccessToken {
    ...
    var token oauth.AccessToken = AuthorizeToken(...)
    return AccessToken(*token)
}

它的意思是“取token的指针值(实际上它根本不是指针,这意味着这是一个语法错误),将其强制转换为AccessToken并返回”。但是该函数返回的是指向AccessToken的指针,而不是一个值,所以这是无效的。

如果你要返回指向AccessToken类型的指针,代码应该更像是这样的:

func Auth(key string, secret string) *AccessToken {
    ...
    token := AccessToken(AuthorizeToken(...))
    return &token
}
英文:

<s>I don't know what error you are getting, but</s> this expression is wrong:

func Auth(key string, secret string) *AccessToken {
...
	var token oauth.AccessToken = AuthorizeToken(...)
	return AccessToken(*token)
}

it's saying "take the pointer-value of token (which is not a pointer at all, meaning it's a syntax error), cast that as AccessToken and return it". But the function returns a pointer to AccessToken, not a value, so this is invalid.

If you are returning a pointer to your AccessToken type, the code should be more along the lines of:

func Auth(key string, secret string) *AccessToken {
...
    token := AccessToken(AuthorizeToken(...))
    return &amp;token
}

huangapple
  • 本文由 发表于 2016年2月23日 21:11:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/35578509.html
匿名

发表评论

匿名网友

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

确定