Skip to main content

Module Constructor

Sometimes it's convenient to have a special function for constructing the main module object. This can, for example, be a simple way to accept module-wide configuration.

Here is an example module with a constructor:

// A Dagger module for saying hello world!

package main

import (
"fmt"
)

func New(
// +optional
// +default="Hello"
greeting string,
// +optional
// +default="World"
name string,
) *MyModule {
return &MyModule{
Greeting: greeting,
Name: name,
}
}

type MyModule struct {
Greeting string
Name string
}

func (hello *MyModule) Message() string {
return fmt.Sprintf("%s, %s!", hello.Greeting, hello.Name)
}

And here is an example call for this module:

dagger call --name=Foo message

The result will be:

Hello, Foo!
note

Dagger Modules have only one constructor. Constructors of custom types are not registered; they are constructed by the function that chains them.

note

If you plan to use constructor fields in other module functions, ensure that they are declared as public. This is because Dagger stores fields using JSON marshalling and private fields are omitted during the marshalling process. As a result, if a field is not declared as public, calling methods that use it will produce unexpected results.