Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define method of struct inside function

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?

like image 933
Anonymous Penguin Avatar asked Aug 15 '15 22:08

Anonymous Penguin


People also ask

Can you define a struct in a function?

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.

Can you put methods in struct?

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.

Can a struct have a method in C?

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 .

Can you have functions inside structs?

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.


1 Answers

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()
}
like image 102
Pandemonium Avatar answered Oct 13 '22 01:10

Pandemonium