亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在函數中初始化通道導致 go routine 死鎖

在函數中初始化通道導致 go routine 死鎖

Go
慕妹3146593 2023-05-04 17:29:24
我是 Go 的新手,所以我確定這是我所缺少的簡單東西。我正在嘗試初始化一個通道以從另一個函數捕獲用戶輸入。我嘗試了以下內容:package inputconst UP = 1const RIGHT = 2const DOWN =3const LEFT = 4var inputChannel chan inttype InputReader interface {  ReadNextInt() int}func InitInputChannel() chan int {  inputChannel := make(chan int, 1)  return inputChannel}func SendInput(inputReader InputReader) {    inputChannel <- inputReader.ReadNextInt()}然后我調用了以下代碼:package inputimport (  "testing"  "github.com/stretchr/testify/assert"  "github.com/stretchr/testify/mock")type MockedInputReader struct {  mock.Mock}func (reader MockedInputReader) ReadNextInt() int {  return 1}func TestShouldSendUpValueToChannelWhenUpKeyPressed(t *testing.T) {  inputReader := new(MockedInputReader)  inputReader.On("ReadNextInt").Return(UP)  receiverChannel := SendInput(inputReader)  actualInput := <- receiverChannel  assert.Equal(t, UP, actualInput)}查看代碼我無法找出問題所在,所以我決定重組一些東西,因為我已經絕望了。我最終得到了以下有效的方法:package inputconst UP = 1const RIGHT = 2const DOWN =3const LEFT = 4var inputChannel chan int = make(chan int, 1)type InputReader interface {  ReadNextInt() int}func SendInput(inputReader InputReader) chan int {    inputChannel <- inputReader.ReadNextInt()    return inputChannel}雖然我很高興它能正常工作,但我很困惑為什么我的第一個解決方案不起作用。當只需要抓取一次時,我也不太愿意為每次 SendInput 調用返回我的頻道。也許 'InputChannel() chan int' getter 會更好?有什么見解嗎?謝謝
查看完整描述

1 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

使用了不正確的變量聲明形式。所以應該做這樣的事情:


package input


const UP = 1

const RIGHT = 2

const DOWN = 3

const LEFT = 4


var inputChannel chan int


type InputReader interface {

? ? ReadNextInt() int

}


func InitChan() chan int {

? inputChannel = make(chan int, 1)

? return inputChannel

}


func SendInput(inputReader InputReader) {

? ? inputChannel <- inputReader.ReadNextInt()

}

要注意的關鍵是“ inputChannel = make(.....) ”,而不是像我之前嘗試的那樣“ inputChannel := make(....) ”。


查看完整回答
反對 回復 2023-05-04
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號