Shorten imported variable exports in Go / Golang?

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

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()
    }
}
  1. 有没有办法将types.S("asdf")缩短为S("asdf")?

  2. 有没有办法将来自其他文件的方法调用转换为小写?例如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()
    }
}
  1. Is there a way to shorten types.S("asdf") to just S("asdf")?

  2. 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

  1. 只要该类型位于与您使用它的包不同的包中,并且不使用点导入,就不会出现这种情况。

  2. 是的,如果另一个文件仍然位于相同的包中。否则,不行,因为函数将不会被导出(对其他包可见)。这是Go的约定。

英文:
  1. Not as long as that type is in a different package from where you're using it, without using dot-imports.

  2. 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.

huangapple
  • 本文由 发表于 2013年8月12日 06:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/18177302.html
匿名

发表评论

匿名网友

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

确定