Me ha surgido esa duda después de estar leyendo Effective-Go y la documentación de golang.org. Para practicar lo que había leído he hecho el siguiente código que me he genera un par de dudas sobre eficiencia y escritura de código en go:
package main
import(
"log"
"strconv"
"fmt"
"github.com/levigross/grequests"
)
type Credentials struct {
url, usr, tkn string
}
//Set the credentials to a client
func (c *Credentials) setCredentials(url, usr, tkn string) {
c.url = url
c.usr = usr
c.tkn = tkn
}
func showTicket(subdomain, usr, tkn string, id int) string {
s := strconv.Itoa(id)
usrTkn := fmt.Sprintf("%s/token", usr)
ro := &grequests.RequestOptions{Auth: []string{usrTkn, tkn}}
path := fmt.Sprintf("/api/v2/tickets/%s.json", s)
url := fmt.Sprintf("%s%s", subdomain, path)
resp, err := grequests.Get(url, ro)
if err != nil {
log.Fatalln("Unable to make request: ", err)
}
return resp.String()
}
func main() {
url := "http://url.com"
usr := "test"
tkn := "1234token"
client := new(Credentials) // returns a pointer to Credentials
client.setCredentials(url, usr, tkn)
id := 1
ticket := showTicket(client.url, client.usr, client.tkn, id)
fmt.Println(ticket)
}
Mis dudas son:
la función setCredentials debería estar en una interface? He leído que las interfaces recogen estados, pero no me queda claro si realmente esto es una función o un estado.
A la hora de concatenar strings, uso el método Sprintf de fmt, pero también he leído que para cosas así es más recomendable usar io.Reader o io.Writer, y no entiendo el por qué, si es por el tema de que ambas trabajan con []bytes o porque son más rápidas, ...
showTicket también no sabría si ponerlo en una interface que fuese Ticket o solo es una función más.
Tengo un problema de comprensión entre cuando usar una interface, una función o usar un método de un struct.