Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Zaxxon
Feb 14, 2004

Wir Tanzen Mekanik

Winkle-Daddy posted:

My question is, can the Name() function take parameters through an interface? What would be the suggested method for passing arguments be? The only way I could think to do it in this example would be to extend the User struct to include any options I want set, then set them when I dereference into the variable "u" which (should) make it accessible to the function the interface calls. That feels kind of dirty though, would that be considered the "go way" of doing things?

e: sorry if this is a dumb question, it's just that everyone says "Start doing things the go way to learn better!" and I'm not exactly sure what the go way is in this case.

I'm not sure what you mean here but you can just pass arguments like a normal function.

code:
package main

import (
	"fmt"
)

type User struct {
	FirstName, LastName string
}

func (u *User) Name(pointlessArg int) string {
	return fmt.Sprintf("%s %s %d", u.FirstName, u.LastName, pointlessArg)
}

type Namer interface {
	Name(int) string
}

func Greet(n Namer) string {
	return fmt.Sprintf("Dear %s", n.Name(15))
}

func main() {
	u := &User{"Matt", "Aimonetti"}
	fmt.Println(Greet(u))
}

Adbot
ADBOT LOVES YOU

Zaxxon
Feb 14, 2004

Wir Tanzen Mekanik

Winkle-Daddy posted:

Hmm, okay, but here:

code:
func main() {
	u := &User{"Matt", "Aimonetti"}
	fmt.Println(Greet(u))
}
What's the syntax for getting my argument into the function since u was passed into Greet? This part is my specific question, which I probably could have asked better.

well, "Greet" doesn't really support this, but greet isn't part of the interface.

All the interface declaration states is that if "x" is a Namer you will be able to do x.Name() and get a string. If the interface states that x.Name takes some arguments it's up to the caller to pass those arguments.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply