Search code examples
goconstructor

Golang Factory Method


I am learning golang, and am getting stuck on an embarassingly simple concept. Maybe it's my OO habits clouding my comprehension, but I can't seem to get this simple example to work:

package main

import (
    "fmt"
)

type datafield struct {
    name  string
    value string
}

func (d datafield) NewField(name, value string) *datafield {
    retval := new(datafield)
    retval.name = name
    retval.value = value
    return retval
}

func main() {
    field := datafield.NewField("name", "value")
    if field == nil {
        fmt.Println("Error: Did not create a datafield")
    } else {
        fmt.Println("Success!")
    }
}

The error is:

prog.go:20:29: not enough arguments in call to method expression datafield.NewField
    have (string, string)
    want (datafield, string, string)

What is the proper way to get NewField(string,string) to create a datafield?


Solution

  • You must not set a method on type "datafield" in your case, but do this instead :

    func NewField(name, value string) *datafield {
        retval := new(datafield)
        retval.name = name
        retval.value = value
        return retval
    }