2

我在这里尝试使用一个简单的模型来测试我对 go 频道的理解。在下面的小片段中,我尝试使用虚假新闻提要的 2 个进程,将多个标题附加到本地数组,然后将其传递给数组字符串通道。在 main 中,我将这些数组传递回不同的打印进程。

编辑:我忘了提到这个问题..我的问题是我不断收到“索引超出边界”异常并且我无法编译代码。

现在我用纯字符串变量尝试了同样的代码,它可以工作。

字符串数组代码:

package main

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

func main() {

    /* initialization and assignment of channels */
    c := make(chan []string)
    p := make(chan []string)

    /* Pass created channels to Goroutines */
    go Feeder1(p)
    go Feeder2(p)
    go Consumer(c)

    for {
        select {
        case produced := <-p:
            c <- produced
        /*case <-time.After(6 * time.Second):
        return*/
        default:
            fmt.Printf("\n --- We timed out! --- \n")
            time.Sleep(5 * time.Second)

        }
    }
}

func Feeder2(w chan []string) {

    headlines := []string{
        "BBC: Speedboat victim 'doted on family'\n",
        "BBC: Syria rebel sarin claim downplayed\n",
        "BBC: German 'ex-Auschwitz guard' arrested\n",
        "BBC: Armless artist 'denied entry' to UK\n",
        "BBC: Bangladesh protest clashes kill 27\n",
        "BBC: Ex-Italian PM Giulio Andreotti dies\n"}

    for i := 0; ; i++ {
        selection := []string{}
        for s := 0; s <= 3; s++ {
            selection[s] = headlines[randInt(0, len(headlines))]
        }
        w <- selection
        time.Sleep(5 * time.Second)
    }
}

func Feeder1(w chan []string) {

    headlines := []string{
        "SKY: Deadly Virus Can 'Spread Between People'\n",
        "SKY: Ariel Castro's Brothers Brand Him 'A Monster'\n",
        "SKY: Astronaut Ends Space Mission With Bowie Song\n",
        "SKY: Chinese Artist Films Violent Street Brawl\n",
        "SKY: May Washout: Fortnight's Rainfall In One Day\n",
        "SKY: Mother's Day Shooting: CCTV Shows Suspect\n"}

    for i := 0; ; i++ {
        selection := []string{}
        for q := 0; q <= 3; q++ {
            selection[q] = headlines[randInt(0, len(headlines))]
        }
        w <- selection
        //randomTimeValue := randInt(5, 6)
        time.Sleep(2 * time.Second)
    }
}

func Consumer(n chan []string) {

    for {
        v := <-n
        for _, x := range v {
            fmt.Printf("Headline:\t%s", x)
        }
    }
}

func randInt(min int, max int) int {
    return min + rand.Intn(max-min)
}

之前运行的代码版本(这里没有数组):

package main

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

func main() {

    /* initialization and assignment of channels */
    c := make(chan string)
    p := make(chan string)

    /* Pass created channels to Goroutines */
    go Feeder1(p)
    go Feeder2(p)
    go Consumer(c)

    for {
        select {

        case produced := <-p:
            c <- produced
        /*case <-time.After(6 * time.Second):
        return*/
        default:
            fmt.Printf("\n --- We timed out! --- \n")
            time.Sleep(5 * time.Second)

        }
    }
}

func Feeder2(w chan string) {
    headlines := []string{
        "BBC: Speedboat victim 'doted on family'\n",
        "BBC: Syria rebel sarin claim downplayed\n",
        "BBC: German 'ex-Auschwitz guard' arrested\n",
        "BBC: Armless artist 'denied entry' to UK\n",
        "BBC: Bangladesh protest clashes kill 27\n",
        "BBC: Ex-Italian PM Giulio Andreotti dies\n"}

    for i := 0; ; i++ {
        w <- headlines[randInt(0, len(headlines))]
        time.Sleep(5 * time.Second)
    }
}

func Feeder1(w chan string) {
    headlines := []string{
        "SKY: Deadly Virus Can 'Spread Between People'\n",
        "SKY: Ariel Castro's Brothers Brand Him 'A Monster'\n",
        "SKY: Astronaut Ends Space Mission With Bowie Song\n",
        "SKY: Chinese Artist Films Violent Street Brawl\n",
        "SKY: May Washout: Fortnight's Rainfall In One Day\n",
        "SKY: Mother's Day Shooting: CCTV Shows Suspect\n"}

    for i := 0; ; i++ {
        w <- headlines[randInt(0, len(headlines))]
        //randomTimeValue := randInt(5, 6)
        time.Sleep(2 * time.Second)
    }
}

func Consumer(n chan string) {

    for {
        v := <-n
        fmt.Printf("Headline:\t%s", v)
    }
}

func randInt(min int, max int) int {
    return min + rand.Intn(max-min)
}

这两个版本都不能在游乐场网站上运行。

谢谢

4

2 回答 2

1

你的问题在这里:

selection := []string{}
for s := 0; s <= 3; s++ {
    selection[s] = headlines[randInt(0, len(headlines))]
}

selection是长度为 0 的切片。当您尝试将值设置为索引 0、1 和 2 时 - 这会导致运行时错误,因为没有为它们分配空间。

初始化切片的首选方法是使用make()

selection := make([]string, 3, 3)
for s := 0; s <= 3; s++ {
    selection[s] = headlines[randInt(0, len(headlines))]
}

第三个参数make()是容量。

另一种可能性是让运行时通过使用隐式增长切片append()

selection := []string{}
for s := 0; s <= 3; s++ {
    selection = append(selection, headlines[randInt(0, len(headlines))])
}

append()将根据需要增长一片。

链接到相关文档

于 2013-05-13T15:40:54.237 回答
0

您的字符串“数组”代码使用的是切片,而不是数组。您正在做 selection[q] = something,但您的切片长度为 0,这应该会引起恐慌。要么:使用 len != 0 制作正确的切片,或者使用数组。

(我个人更喜欢游乐场代码)。

于 2013-05-13T15:35:20.803 回答