我是 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(....) ”。
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消