英文:
Shorten imported variable exports in Go / Golang?
问题
以下是翻译的内容:
如果我有
// types.go
type S string
func (s *S) Lower() *S {
*s = S(strings.ToLower(string(*s)))
return s
}
`
// in another file
import "u/types"
func main() {
s := types.S("asdf")
if s == "asdf" {
s.Lower()
}
}
-
有没有办法将types.S("asdf")缩短为S("asdf")?
-
有没有办法将来自其他文件的方法调用转换为小写?例如s.Lower() => s.lower()?
英文:
if I have
// types.go
type S string
func (s *S) Lower() *S {
*s = S(strings.ToLower(string(*s)))
return s
}
`
// in another file
import "u/types"
func main() {
s := types.S("asdf")
if s == "asdf" {
s.Lower()
}
}
-
Is there a way to shorten types.S("asdf") to just S("asdf")?
-
Is there a way to lowercase method calls from other files? e.g. s.Lower() => s.lower()?
答案1
得分: 13
这不是大多数情况下的推荐做法,但你可以使用import . "u/types"
来导入所有的公共符号,并跳过类型前缀。.
将会为你的包导入所有的公共符号,使你可以像调用本地符号一样调用它们。
英文:
It's not recommended for most cases but you can do import . "u/types"
and all then skip the types prefix. .
will import all the public symbols into your package for you allowing you to call them as if they were local to your package.
答案2
得分: 0
-
只要该类型位于与您使用它的包不同的包中,并且不使用点导入,就不会出现这种情况。
-
是的,如果另一个文件仍然位于相同的包中。否则,不行,因为函数将不会被导出(对其他包可见)。这是Go的约定。
英文:
-
Not as long as that type is in a different package from where you're using it, without using dot-imports.
-
Yes, if the other file is still in the same package. Otherwise, no, because then the function won't be exported (visible to other packages). This is Go convention.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论