I have this code
func baz() {
type mockDatabase struct{}
//
// More code
//
}
I want to define a method of mockDatabase
, so the full code would look like this:
func baz() {
type mockDatabase struct{}
func (m *mockDatabase) Foo() {
// Implement function here
}
//
// More code
//
}
The reason I want to do this is I'm injecting a dependency into a function, and I want to create a "mock object" to inject into the function (the function takes an interface as an argument and the mock object will implement the interface).
I could create the struct outside, but it seems more logical to declare the struct locally to decrease namespace clutter, especially when these mock objects will only be used once. Am I missing something here? Is it better practice to define it outside the test function so it's not long? What should I do here?
No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Show activity on this post.
The above code snippet creates an instance of the Rectangle struct and assigns values to the public members of it. Note that you can have both member data and methods inside a struct.
Contrary to what younger developers, or people coming from C believe at first, a struct can have constructors, methods (even virtual ones), public, private and protected members, use inheritance, be templated… just like a class .
Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.
The idiomatic Go would be to use package for namespacing.
package mock
type MockDatabase struct {}
func (m *mockDatabase) Foo() {}
In the main code, you can call from the package
package main
import (
"path/to/mock"
)
var m = New(mock.MockDatabase)
func baz() {
m.Foo()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With