相关疑难解决方法(0)

表测试 Go 泛型

我对 Go 1.18 感到很兴奋,并想测试新的泛型功能。使用起来感觉很简洁,但我偶然发现了一个问题:

如何对通用函数进行表测试?

我想出了这段代码,但我需要重新声明每个函数的测试逻辑,因为我无法实例化T值。(在我的项目中,我使用结构而不是stringand int。只是不想包含它们,因为它已经有足够的代码了)

您将如何解决这个问题?

编辑:这是代码:

package main

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

type Item interface {
    int | string
}

type store[T Item] map[int64]T

// add adds an Item to the map if the id of the Item isn't present already
func (s store[T]) add(key int64, val T) {
    _, exists := s[key]
    if exists {
        return
    }
    s[key] = val
}

func TestStore(t *testing.T) {
    t.Run("ints", testInt)
    t.Run("strings", …
Run Code Online (Sandbox Code Playgroud)

generics testing unit-testing go

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

具有不同运行时类型的通用容器

我目前正在尝试通过通道将数据发送到 goroutine,然后 goroutine 会进一步处理它。我的问题是我希望通道能够适用于任何类型。为此,我研究了 Go 1.18 中新引入的泛型。

我的问题是,当我启动 goroutine 时,我需要告诉它通道的类型,这是不可能告诉的,因为它可以保存任何数据。

这就是我现在得到的:

线:

func StartController[T any](sender chan Packet[T]) {
    go runThread(sender)
}

func runThread[T any](sender chan Packet[T]) {
    fmt.Println("in thread")
    for true {
        data := <- sender

        fmt.Println(data)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试功能是这样的:

func main() {
    sender := make(chan Packet)

    StartController(sender)

    sender <- Packet[int]{
        Msg: Message[int]{
            Data: 1,
        },
    }

    sender <- Packet[string]{
        Msg: Message[string]{
            Data: "asd",
        },
    }

    for true {}
}
Run Code Online (Sandbox Code Playgroud)

类型:

type Message[T any] struct {
    Data T
}

type …
Run Code Online (Sandbox Code Playgroud)

generics channel go

3
推荐指数
1
解决办法
3196
查看次数

返回 Golang 中的联合类型

我想尝试 Golang 中的联合类型实现,就像在这个答案
中 我尝试这样做:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

type intOrString interface {
    int | string
}

func main() {
    fmt.Println(measure())

}
func measure[T intOrString]() T {
    rand.Seed(time.Now().UnixNano())
    min := 20
    max := 35
    temp := rand.Intn(max-min+1) + min

    switch {
    case temp < 20:
        return "low" //'"low"' (type string) cannot be represented by the type T
    case temp > 20:
        return T("high") //Cannot convert an expression of the type 'string' to the type 'T' …
Run Code Online (Sandbox Code Playgroud)

go

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

标签 统计

go ×3

generics ×2

channel ×1

testing ×1

unit-testing ×1