LoginSignup
5

More than 5 years have passed since last update.

Golangでメソッドチェーン

Last updated at Posted at 2015-01-17

もっといい方法があるかと思いますが

シンプルに

package main

import (
    "fmt"
)

type Term struct {
}

func (e *Term)ex1() *Term {
    fmt.Println("1")
    return e
}

func (e *Term)ex2() *Term {
    fmt.Println("2")
    return e
}


func (e *Term)ex3() *Term {
    fmt.Println("3")
    return e
}

func main() {
    e := &Term{}
    e.ex1().ex2().ex3()
}

たとえばデータベース操作で

エラー処理、セッション関係と実際の処理は省いています

package main

type DbTerm struct {
    dbName string
    tableName string
}

func Db(dbName string) *DbTerm {
    term := &DbTerm{dbName, ""}
    return term
}

func (e *DbTerm) Table(tableName string) *DbTerm {
    term := &DbTerm{e.dbName, tableName}
    return term
}

func (e *DbTerm) Insert(data map[string]interface{}) error {
    //Insert処理
}

func main() {

    data := map[string]interface{} {"testkey":"testvalue"}

    err := Db("testdb").Table("testtable").Insert(data)

    if err != nil ...
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5