I am new to Go so I'm sure this is something simple I am missing. I am trying to initialize a channel to capture user input from another function. I tried the following:
package input
const UP = 1
const RIGHT = 2
const DOWN =3
const LEFT = 4
var inputChannel chan int
type InputReader interface {
ReadNextInt() int
}
func InitInputChannel() chan int {
inputChannel := make(chan int, 1)
return inputChannel
}
func SendInput(inputReader InputReader) {
inputChannel <- inputReader.ReadNextInt()
}
I then called the code with the following:
package input
import (
"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)
}
Looking at the code I just couldn't figure out the issue so I decided to restructure some things since I was getting desperate. I ended up with the following which worked:
package input
const UP = 1
const RIGHT = 2
const DOWN =3
const LEFT = 4
var inputChannel chan int = make(chan int, 1)
type InputReader interface {
ReadNextInt() int
}
func SendInput(inputReader InputReader) chan int {
inputChannel <- inputReader.ReadNextInt()
return inputChannel
}
While I am glad that I got it working I am confused why my first solution didn't work. I am also not really crazy about returning my channel for every single SendInput call when it only needs grabbed once. Maybe a 'InputChannel() chan int' getter would be better? Any insight? Thanks
As ThunderCat mentioned in the comments on my question, I was using the incorrect form of variable declaration. So I should have done something like this:
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()
}
The key to notice is the 'inputChannel = make(.....)' rather than 'inputChannel := make(....)' like I was trying before.