登录
首页 >  Golang >  Go问答

为什么这个goroutine的行为类似于使用引用传递?

来源:stackoverflow

时间:2024-03-21 11:15:44 434浏览 收藏

尽管 tryField 函数是按值调用的,但其参数 b(一个 board 类型)包含对底层数组的引用。当 goroutine 修改 b 的字段时,这些更改也会影响其他 goroutine 中的 b,因为它们都指向同一底层数组。因此,该行为类似于引用传递,其中对变量的更改会影响所有引用该变量的 goroutine。

问题内容

我正在尝试学习 go 的基础知识,但我对我测试的代码片段中按值调用和按引用调用之间的区别有点困惑。

我尝试解决一个编码游戏难题,其中需要计算井字游戏字段的解决方案。

我正在使用的代码

因为我正在学习go,所以我想使用一个goroutine来测试井字棋盘的每个字段,检查该字段是否是解决方案,然后将指向该字段的指针放入主通道中方法得到结果。我使用的代码如下所示:

package main

import "fmt"
import "os"

var player int = int('O')
var opponent int = int('X')
var empty int = int('.')

type board struct {
    fields [][]int
}

func main() {
    lines := [3]string {"OO.", "...", "..."}

    var b board
    b.fillBoard(lines)
    fmt.Fprintln(os.Stderr, "input board:")
    b.printBoard(true)

    resultChannel := make(chan *board)
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            go tryField(b, [2]int{i, j}, resultChannel) // goroutine call that isn't working as expected
        }
    }

    fmt.Fprintln(os.Stderr, "\nresult:")
    for i := 0; i < 9; i++ {
        resultBoard := <- resultChannel
        if (resultBoard != nil) {
            resultBoard.printBoard(false)
            return
        }
    }
    
    // fmt.Fprintln(os.Stderr, "Debug messages...")
    fmt.Println("false")// Write answer to stdout
}

func tryField(b board, field [2]int, result chan *board) {
    b.printBoard(true)
    fmt.Fprintln(os.Stderr, "add O to field: ", field)
    fmt.Fprint(os.Stderr, "\n")
    if (b.fields[field[0]][field[1]] != empty) {
        result <- nil
    }

    b.fields[field[0]][field[1]] = player
    if (b.isWon()) {
        result <- &b
    } else {
        result <- nil
    }
}


func (b *board) fillBoard(lines [3]string) {
    b.fields = make([][]int, 3)
    for i := 0; i < 3; i++ {
        b.fields[i] = make([]int, 3)
    }

    for i, line := range lines {
        for j, char := range line {
            b.fields[i][j] = int(char)
        }
    }
}

func (b *board) printBoard(debug bool) {
    var stream *os.File
    if (debug) {
        stream = os.Stderr
    } else {
        stream = os.Stdout
    }
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            fmt.Fprint(stream, string(b.fields[i][j]))
        }
        fmt.Fprint(stream, "\n")
    }
}

func (b *board) isWon() bool {
    for i := 0; i < 3; i++ {
        rowFull := true
        colFull := true
        for j := 0; j < 3; j++ {
            rowFull = rowFull && b.fields[i][j] == player
            colFull = rowFull && b.fields[j][i] == player
        }
        if (rowFull || colFull) {
            return true
        }
    }

    diagonal1Full := true
    diagonal2Full := true
    for i := 0; i < 3; i++ {
       diagonal1Full = diagonal1Full && b.fields[i][i] == player
       diagonal2Full = diagonal2Full && b.fields[i][2-i] == player
    }

    if (diagonal1Full ||diagonal2Full) {
        return true
    }

    return false
}

您可以在演示中运行它。

问题

由于代码片段中的最后一个函数被声明为 func tryfield(b board, field [2]int, result chan *board) 我假设板 b 是一个独立的副本,每次调用该方法时,因为这是按值调用。因此,更改此板不应影响其他 goroutine 中的其他板。但不幸的是,更改一个 goroutine 中的 board 确实会影响其他 goroutine 中的 board,因为程序的输出如下:

输入板: 哦。 ... ... 结果: 哦。 ... ... 将 o 添加到字段:[1 0] 哦。 奥.. ... 将 o 添加到字段:[2 1] 哦。 奥.. .o.

正如您所看到的,初始字段在第一行的第一列和第二列有两个 o。将 o 添加到位置 [1 0] 的效果与预期一致,但是当将 o 添加到字段 [2 1] 时,在 [1 0] 处也有一个 o,它是在前一个 goroutine 中添加的,不应该因为它是按值调用的。

问题

为什么我的代码片段中的代码表现得像通过引用调用,尽管该函数不使用指针?

提前致谢!


正确答案


切片是对数组的引用。当修改切片而不复制它时,底层数组将被修改。因此,指向同一底层数组的所有切片都会看到此更改。

终于介绍完啦!小伙伴们,这篇关于《为什么这个goroutine的行为类似于使用引用传递?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>