小编Yuv*_*rer的帖子

为什么这段代码在Go O(n²)中而不是O(n)中?

我正在阅读《有效的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)复杂。

go time-complexity

5
推荐指数
1
解决办法
122
查看次数

如何使用较少的字段将结构转换为其他结构

我试图将类型为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 …

struct go

4
推荐指数
1
解决办法
76
查看次数

标签 统计

go ×2

struct ×1

time-complexity ×1