To John:
I have to agree with you there. I compile time check is much preferred
to a run-time check.
To Rodrigo:
I don't think a panic() is necessary. There are other ways to handle
the extra arguments as illustrated in my response below.
To anonymous:
Let's use a hypothetical scenario. An object 'Foo' has a property
called 'name'. I need to be able to retrieve the object's name and set
a new one after it has been instantiated. Too protect the object's
integrity I can't access its internal private variables, only it's
public members:
struct Foo {
name string
}
// setter function
func (f *Foo) SetName(name string) {
f.name = name
}
// getter function
func (f* Foo) Name() string {
return
f.name
}
// unified getter/setter
func (f *Foo) Name(name ...string) string, os.Error {
switch len(name) {
case 0:
return
f.name, nil
case 1:
f.name = name[0]
return nil, nil
default: // invalid argument count
return os.NewError(fmt.Sprintf("Invalid argument count. Expected
1, got %d.", len(name))
}
// a slightly different implementation of the unified approach
func (f *Foo) Name2(name ...string) string {
x := len(name)
switch {
if !x {
return
f.name
}
f.name = name[0] // discard/ignore any additional arguments
}
Does that help illustrate my question? I want to know which approach
is better in Go. I think the answer is two separate functions due to
the compile-time checking as John points out. Though, I do like only
having one function to do everything.
My favorite thing about Go is that there are many ways to accomplish
the same task easily.
Rob