go - 检查结构中的每个项目是否未更改

标签 go struct comparison

我有以下包:

// Contains state read in from the command line
type State struct {
    Domain          string  // Domain to check for
    DomainList      string  // File location for a list of domains
    OutputNormal    string  // File to output in normal format
    OutputDomains   string  // File to output domains only to
    Verbose         bool    // Verbose prints, incl. Debug information
    Threads         int     // Number of threads to use
    NoColour        bool    // Strip colour from output
    Silent          bool    // Output domains only
    Usage           bool    // Print usage information
}

func InitState() (state State) {
    return State { "", "", "", "", false, 20, false, false, false }
}

func ValidateState(s *State) (result bool, error string ) {
    if s.Domain == "" && s.DomainList == "" {
        return false, "You must specify either a domain or list of domains to test"
    }

    return true, ""
}

ValidateState() 中,如果 State 中的每一项都与 InitState() 中定义的相同,我想返回 true .我可以看到一些方法来做到这一点,但没有一个看起来简洁。我会非常重视一些方向!

最佳答案

如果结构值的所有字段都具有可比性(参见 Spec: Comparison operators ),则结构值是可比的。由于在您的情况下这成立,我们可以利用这一点。

在您的情况下,实现此目的的最简单和最有效的方法是保存一个包含初始值的结构值,并且每当您想要判断一个结构值(如果它的任何字段)是否已更改时,只需将它与保存的初始值。这就是全部:

var defaultState = InitState()

func isUnchanged(s State) bool {
    return s == defaultState
}

测试它:

s := InitState()
fmt.Println(isUnchanged(s))

s.Threads = 1
fmt.Println(isUnchanged(s))

输出(在 Go Playground 上尝试):

true
false

请注意,如果您通过添加/删除/重命名/重新排列字段来更改 State 类型,只要它们仍然具有可比性,此解决方案仍然可以在不进行任何修改的情况下工作。作为反例,如果您添加一个 slice 类型的字段,它将不再起作用,因为 slice 不可比较。它将导致编译时错误。要处理此类情况,reflect.DeepEqual()可以用来代替简单的 == 比较运算符。

另请注意,您应该像这样创建 State 的默认值:

func NewState() State {
    return State{Threads: 20}
}

您不必列出值为其类型的零值的字段。

关于go - 检查结构中的每个项目是否未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423265/

相关文章:

comparison - 大多数 Web 应用程序遗漏了桌面应用程序的哪些常见功能?

python - 类似于本地文件的 HTTP Headers 的属性系统

c - 在数组中使用 int 还是 char?

string - 如何在Go中将整数转换为固定长度的十六进制字符串?

c - 设置 tcp header 中的最大段大小

c - C 结构上的共享内存无法正常工作

javascript - 如何检查对象中的字符串在数组中是否唯一

unit-testing - ScalaTest 和 Scala Specs 单元测试框架有什么区别?

go - 为什么在 Golang 中使用 fmt.Println(slice) 打印 slice 不同

function - 戈朗 : Stack multiple method calls on one line