struct{}空结构体怎么在Golang中使用

发布时间:2021-01-15 17:20:18 作者:Leah
来源:亿速云 阅读:285

struct{}空结构体怎么在Golang中使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

golang 空结构体 struct{} 可以用来节省内存

a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0

理由如下:

  1. 如果使用的是map,而且map又很长,通常会节省不少资源

  2. 空struct{}也在向别人表明,这里并不需要一个值

本例说明在map里节省资源的用途:

set := make(map[string]struct{})
for _, value := range []string{"apple", "orange", "apple"} {
  set[value] = struct{}{}
}
fmt.Println(set)
// Output: map[orange:{} apple:{}]

下例,演示了struct{}可以向人展示对象中不需要任何数据,仅包含需要方法。在调用也并无任何区别

type Lamp struct{}

func (l Lamp) On() {
    println("On")

}
func (l Lamp) Off() {
    println("Off")
}

func main() {
    // Case #1.
    var lamp Lamp
    lamp.On()
    lamp.Off()
    // Output:
    // on
    // off
 
    // Case #2.
    Lamp{}.On()
    Lamp{}.Off()
    // Output: 
    // on
    // off
}

还有其他情况,比如有时候使用channel,但并不需要附带任何数据。

func worker(ch chan struct{}) {
 // Receive a message from the main program.
 <-ch
 println("roger")
 
 // Send a message to the main program.
 close(ch)
}

func main() {
 ch := make(chan struct{})
 go worker(ch)
 
 // Send a message to a worker.
 ch <- struct{}{}
 
 // Receive a message from the worker.
 <-ch
 println(“roger")
 // Output:
 // roger
 // roger
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Golang的fallthrough与switch的坑
  2. 一、配置GO环境及安装IDE

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

golang struct{}

上一篇:using语法糖怎么在C# 运用

下一篇:PyCharm无法打开新项目如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》