我正在阅读《有效的Go》,其中有一段代码我觉得很O(n)复杂,但确实如此O(n²)。为什么将此for range循环视为O(n²)?
可以在这里找到(在#interfaces下)
type Sequence []int
...
func (s Sequence) String() string {
...
for i, elem := range s { // Loop is O(N²); will fix that in next example.
if i > 0 {
str += " "
}
str += fmt.Sprint(elem)
}
...
}
Run Code Online (Sandbox Code Playgroud)
我认为这是O(n)因为在上仅存在一次迭代s,并且该if语句fmt.Sprint不应该很O(n)复杂。
我试图将类型为Big的结构复制为类型Small,而不用相同的字段显式创建类型为Small的新结构。
我试图寻找其他类似问题,比如这个和这个尚未完全不同结构类型之间的转换发生只有在结构具有相同的字段。
这是我尝试做的一个例子:
// Big has all the fields that Small has including some new ones.
type Big struct {
A int
B string
C float
D byte
}
type Small struct {
A int
B string
}
// This is the current solution which I hope to not use.
func ConvertFromBigToSmall(big Big) Small {
return Small{
A: big.A,
B: big.B,
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够做这样的事情,但是不起作用:
big := Big{}
small := Small(big)
Run Code Online (Sandbox Code Playgroud)
有没有之间进行转换的方式Big,以Small不使用(甚至反之亦然)Convert …