主要原因是能够实现接口,这些接口指示具有特定参数的特定方法,即使您没有在实现中使用所有这些方法。这在@Jsor 的回答中有详细说明。
另一个很好的理由是,未使用的(局部)变量通常是错误或使用语言特性的结果(例如,在块中使用短变量声明 :=,无意中隐藏了“外部”变量)而未使用的函数参数从不(或很少)是错误的结果。
另一个原因可能是提供向前兼容性。如果你发布了一个库,你就不能在不破坏向后兼容性的情况下更改或扩展参数列表(在 Go 中没有函数重载:如果你想要 2 个具有不同参数的变体,它们的名称也必须不同)。
您可以提供一个导出的函数或方法,并向其中添加额外的 - 尚未使用的 - 或可选参数(例如 hints),以便您可以在未来的版本/发行版中使用它们你的图书馆。
尽早这样做会给您带来好处,即使用您的库的其他人无需更改其代码中的任何内容。
我们来看一个例子:
你想创建一个格式化函数:
// FormatSize formats the specified size (bytes) to a string.
func FormatSize(size int) string {
return fmt.Sprintf("%d bytes", size)
}
你也可以马上添加一个额外的参数:
// FormatSize formats the specified size (bytes) to a string.
// flags can be used to alter the output format. Not yet used.
func FormatSize(size int, flags int) string {
return fmt.Sprintf("%d bytes", size)
}
稍后您可以改进您的库和您的 FormatSize() 函数以支持以下格式标志:
const (
FlagAutoUnit = 1 << iota // Automatically format as KB, MB, GB etc.
FlagSI // Use SI conversion (1000 instead of 1024)
FlagGroupDecimals // Format number using decimal grouping
)
// FormatSize formats the specified size (bytes) to a string.
// flags can be used to alter the output format.
func FormatSize(size int, flags int) string {
var s string
// Check flags and format accordingly
// ...
return s
}