Subscribed unsubscribe Subscribe Subscribe

Go のサンプルいくつか

go google golang

Methods:

package main

import "log";

type string_list struct {
    items []string;
}

func (self *string_list) Join(sep string)(string) {
    retval := "";
    for i := 0; i < len(self.items); i++ {
        if i > 0 { retval += sep; }
        retval += self.items[i];
    }
    return retval;
}

func main() {
    log.Stdout((string_list{ items: []string { "え", "っ", "ち" } }).Join("-"));
}

Interfaces:

package main

import (
    "log";
    "strconv";
)

type string_list struct {
    nitems int;
    items []string;
}

type int_list struct {
    nitems int;
    items []int;
}

type list interface {
    len()(int);
    get(int)(string);
    add(string);
}

func min(a int, b int)(int) {
    if a < b { 
        return a;
    }
    return b;
}

func (self *string_list) len()(int) {
    return self.nitems;
}

func (self *int_list) len()(int) {
    return self.nitems;
}

func (self *string_list) get(n int)(string) {
    return self.items[n];
}

func (self *int_list) get(n int)(string) {
    return strconv.Itoa(self.items[n]);
}

func (self *string_list) resize(n int) {
    new_items := make([]string, n);
    nitems := len(self.items);
    c := min(nitems, n);
    for i := 0; i < c; i++ {
        new_items[i] = self.items[i]
    }
    self.items = new_items;
}

func (self *int_list) resize(n int) {
    new_items := make([]int, n);
    nitems := len(self.items);
    c := min(nitems, n);
    for i := 0; i < c; i++ {
        new_items[i] = self.items[i]
    }
    self.items = new_items;
}

func (self *string_list) add(item string) {
    if self.nitems >= len(self.items) {
        if self.nitems == 0 {
            self.resize(16)
        } else {
            self.resize(self.nitems * 2)
        }
    }
    self.items[self.nitems] = item;
    self.nitems += 1;
}

func (self *int_list) add(item int) {
    if self.nitems >= len(self.items) {
        if self.nitems == 0 {
            self.resize(16)
        } else {
            self.resize(self.nitems * 2)
        }
    }
    self.items[self.nitems] = item;
    self.nitems += 1;
}

func foreach(items list, fun func(string)) {
    for i := 0; i < items.len(); i++ {
        fun(items.get(i)); 
    }
}

func main() {
    slist := new(string_list);
    log.Stdout("len=", slist.len());
    slist.add("test");
    log.Stdout("len=", slist.len());
    foreach(slist, func(__ string) { log.Stdout(__); } );

    ilist := new(int_list);
    log.Stdout("len=", ilist.len());
    ilist.add("test");
    log.Stdout("len=", ilist.len());
    // int_list は add(item string) を実装していないので、
    // 次の行でエラーになる
    foreach(ilist, func(__ string) { log.Stdout(__); } );
}

ちょいと試すなら fmt.Printf() より log.Stdout() の方がおてがるですね。