名为"_"的字段的目的是什么? (下划线)包含一个空结构? [英] What is the purpose of a field named "_" (underscore) containing an empty struct?

查看:40
本文介绍了名为"_"的字段的目的是什么? (下划线)包含一个空结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了使用这种模式的两段Go代码:

I've seen two pieces of Go code using this pattern:

type SomeType struct{
  Field1 string
  Field2 bool
  _      struct{}    // <-- what is this?
}

任何人都可以解释这段代码的作用吗?

Can anyone explain what this code accomplishes?

推荐答案

此技术在声明结构时强制执行键控字段.

This technique enforces keyed fields when declaring a struct.

例如,结构:

type SomeType struct {
  Field1 string
  Field2 bool
  _      struct{}
}

只能用键控字段声明:

// ALLOWED:
bar := SomeType{Field1: "hello", Field2: "true"}

// COMPILE ERROR:
foo := SomeType{"hello", true}

这样做的原因之一是允许将来在不破坏现有代码的情况下将其他字段添加到结构中.

One reason for doing this is to allow additional fields to be added to the struct in the future without breaking existing code.

这篇关于名为"_"的字段的目的是什么? (下划线)包含一个空结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆