Chaining functions in Go?

go

Solution

This works:

package main

import (
    "fmt"
    "strings"
)

type String string


func (s *String) tolower() *String {
    *s = String(strings.ToLower(string(*s)))
    return s
}

func (s *String) toupper() *String {
    *s = String(strings.ToUpper(string(*s)))
    return s
}

func main() {
    var s String = "ASDF"
    (s.tolower()).toupper()
    s.toupper();
    s.tolower();
    s.tolower().toupper()
    fmt.Println(s)
}

Your return type is of String, for functions defined on pointers to String. It wouldn't make sense to be able to chain them.

Problem

I tried doing this: ``` package main import ( "fmt" "strings" ) type String string func (s *String) tolower() String { *s = String(strings.ToLower(string(*s))) return *s } func (s *String) toupper() String { *s = String(strings.ToUpper(string(*s))) return *s } func main() { var s String = "ASDF" (s.tolower()).toupper() // this fails // s.toupper();s.tolower(); // this works // s.tolower().toupper() // this fails too fmt.Println(s) } ``` But I got these errors: ``` prog.go:30: cannot call pointer method on s.tolower() prog.go:30: cannot take the address of s.tolower() Program exited. ``` Why can't I make this chain work?

Original source