func worker(done chan bool) {
	spew.Printf("working...\n")
	time.Sleep(time.Second)
	spew.Printf("done!\n")

	done <- true
}
Esempio n. 2
0
func main() {
	nums := []int{2, 3, 4}

	// for ... range は for の中で initialize できない。
	sum := 0
	for _, num := range nums {
		sum += num
	}
	spew.Printf("sum: %#+v\n", sum)

	// ちなみにここでも num をまた宣言 & 代入してるけど、これは OK である。
	// 新規 + 既存 := で多値を受け取る場合は、既存変数を再宣言 & 再代入しても
	// エラーにはならない。なお、同一スコープな否ならアドレス番地は同じになっている。
	//  [Go言語で複数戻り値の受け取りで既存変数の再宣言? - taknb2nchのメモ]
	//  http://d.hatena.ne.jp/taknb2nch/20140819/1408421727
	for i, num := range nums {
		if num == 3 {
			spew.Printf("index: %#+v\n", i)
		}
	}

	kvs := map[string]string{"a": "apple", "b": "banana"}
	for k, v := range kvs {
		spew.Printf("%#+v -> %#+v\n", k, v)
	}

	for i, c := range "号号" {
		spew.Printf("%#+v -> %#+v\n", i, c)
	}
}
Esempio n. 3
0
func main() {
	res := plus(1, 2)
	spew.Printf("1 + 2 = %#+v\n", res)

	res = plusPlus(1, 2, 3)
	spew.Printf("1 + 2 + 3 = %#+v\n", res)
}
Esempio n. 4
0
func main() {
	c1 := make(chan string, 1)
	go func() {
		time.Sleep(time.Second * 2)
		c1 <- "result 1"
	}()

	select {
	case res := <-c1:
		spew.Printf("%#+v\n", res)

	case <-time.After(time.Second * 1):
		spew.Printf("timeout 1\n")
	}

	c2 := make(chan string, 1)
	go func() {
		time.Sleep(time.Second * 2)
		c2 <- "result 2"
	}()

	select {
	case res := <-c2:
		spew.Printf("%#+v\n", res)
	case <-time.After(time.Second * 3):
		spew.Printf("timeout 2\n")
	}
}
Esempio n. 5
0
func main() {
	timer1 := time.NewTimer(time.Second * 2)
	// Timer 構造体のポインタが返ってくる様子。
	spew.Printf("%#+v\n", timer1)

	// 経過した時の時刻が入るっぽいな。
	ret := <-timer1.C
	spew.Printf("%#+v\n", ret)
	fmt.Println("Timer 1 expired", ret)

	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()

	// stop2 := timer2.Stop()
	// if stop2 {
	// 	spew.Printf("%#+v\n", stop2)
	// 	fmt.Println("Timer 2 stopped")
	// }

	// ゴルーチンの終了を待ったら当然結果が出力されるし、
	// timer2 は expired しちゃってるから Stop() も動作しない。
	// time.Sleep(time.Second * 3)
	// こうでよくね。
	if timer2.Stop() {
		fmt.Println("Timer 2 stopped")
	}
}
Esempio n. 6
0
func main() {

	apiUser := os.Getenv(ApiUser)
	apiKey := os.Getenv(ApiKey)

	id := 12345

	client := slclient.NewSoftLayerClient(apiUser, apiKey)

	virtualGuestService, err := client.GetSoftLayer_Virtual_Guest_Service()

	if err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println("No error found in client.GetSoftLayer_Virtual_Guest_Service()")
	}

	virtualGuest, err := virtualGuestService.GetObject(id)

	if err != nil {
		fmt.Println("errors:", err)
		return
	} else {
		fmt.Println("No error found in virtualGuestService.GetObject(id)")
	}

	spew.Printf("virtualGuest =%#+v\n", virtualGuest)

	vgPowerState, err := virtualGuestService.GetPowerState(id)

	spew.Printf("vgPowerState =%#+v\n", vgPowerState)
}
func sum(nums ...int) {
	spew.Printf("nums: %#+v\n", nums)
	total := 0
	for _, num := range nums {
		total += num
	}
	spew.Printf("total: %#+v\n\n", total)
}
func main() {
	a, b := vals()
	spew.Printf("a: %#+v\n", a)
	spew.Printf("b: %#+v\n", b)

	_, c := vals()
	spew.Printf("c: %#+v\n", c)
}
Esempio n. 9
0
func main() {
	// int
	var i int = 1
	var pi *int = &i

	// string
	var str string = "hello, world."
	var pstr *string = &str

	// array
	var ary [2]int = [2]int{1, 2}
	var pary *[2]int = &ary

	// slice
	var slc []int = []int{10, 20}
	var pslc *[]int = &slc

	// これは分かる。
	spew.Println("int")
	spew.Printf("i = %#+v, &i = %#+v, pi = %#+v, *pi = %#+v\n\n", i, &i, pi, *pi)

	spew.Println("string")
	spew.Printf("str = %#+v, &str = %#+v, pstr = %#+v, *pstr = %#+v\n\n", str, &str, pstr, *pstr)

	spew.Println("array")
	spew.Printf("ary = %#+v, &ary = %#+v, pary = %#+v, *pary = %#+v\n\n", ary, &ary, pary, *pary)

	spew.Println("slice")
	spew.Printf("slc = %#+v, &slc = %#+v, pslc = %#+v, *pslc = %#+v\n\n", slc, &slc, pslc, *pslc)

	// 解せぬ。
	spew.Println("string[n]")
	// &str[0]: cannot take the address of str[0] // 文字列の要素をアドレス番地 + 添字で求められないのは仕様である、といった感じであろうか?
	// pstr[0]: invalid operation: pstr[0] (type *string does not support indexing) // 上と同様。
	// *pstr[0]: invalid operation: pstr[0] (type *string does not support indexing) // なぜだ。
	spew.Printf("str[0] = %#+v\n\n", str[0])

	spew.Println("array[n]")
	// *pary[0]: invalid indirect of pary[0] (type int) // なぜだ。
	spew.Printf("ary[0] = %#+v, &ary[0] = %#+v, pary[0] = %#+v\n\n", ary[0], &ary[0], pary[0])

	spew.Println("slice[n]")
	// pslc[0]: invalid operation: pslc[0] (type *[]int does not support indexing) // スライスはそれ自体がすでにどこかのアドレス番地の参照先のはず。スライスのポインタはダブルポインタ的な感じなので、アドレス番地 + 添字で求められないのは仕様である、といった感じだろうか?
	// *pslc[0]: invalid operation: pslc[0] (type *[]int does not support indexing) // なぜだ。
	spew.Printf("slc[0] = %#+v, &slc[0] = %#+v\n\n", slc[0], &slc[0])

	// できるじゃん。
	spew.Println("(*string)[n]")
	spew.Printf("(*pstr)[0] = %#+v\n\n", (*pstr)[0])

	spew.Println("(*array)[n]")
	spew.Printf("(*pary)[0] = %#+v\n\n", (*pary)[0])

	spew.Println("(*pscl)[n]")
	spew.Printf("(*pslc)[0] = %#+v\n\n", (*pslc)[0])
}
func main() {
	messages := make(chan string, 2)

	messages <- "buffered"
	messages <- "channel"

	spew.Printf("%#+v\n", &messages)
	spew.Printf("%#+v\n", <-messages)
	spew.Printf("%#+v\n", <-messages)
}
Esempio n. 11
0
func main() {
	strs := []string{"c", "a", "b"}
	sort.Strings(strs)
	spew.Printf("Strings: %#+v\n", strs)

	ints := []int{7, 2, 4}
	sort.Ints(ints)
	spew.Printf("Intss: %#+v\n", ints)

	s := sort.IntsAreSorted(ints)
	spew.Printf("Sorted: %#+v\n", s)
}
Esempio n. 12
0
func main() {
	i := 1
	spew.Printf("initial: %#+v\n", i)

	zeroval(i)
	spew.Printf("zeroval: %#+v\n", i)

	zeroptr(&i)
	spew.Printf("zeroptr: %#+v\n", i)

	spew.Printf("pointer: %#+v\n", &i)
}
func main() {
	//* key / varlue ペアを設定するために、'''os.Setenv''' を使います。key から value を取得するために '''os.Getenv''' を使います。環境に key が存在しない場合は空文字が返ります。
	os.Setenv("FOO", "1")
	spew.Printf("FOO: %#+v\n", os.Getenv("FOO"))
	spew.Printf("BAR: %#+v\n", os.Getenv("BAR"))
	spew.Printf("$PGUSER: %#+v\n", os.Getenv("PGUSER"))

	//* '''os.Environ''' を使うと、環境内の全ての key / value ペアがリストされます。これは '''key=value''' という形式の文字列スライスです。ここで私達は全ての key を出力しています。
	spew.Println()
	for _, e := range os.Environ() {
		pair := strings.Split(e, "=") // e: "key=value" --- strings.Split() ---> pair:["key", "value"]
		spew.Println(pair[0])
	}
}
Esempio n. 14
0
func getStat() {
	sTime := time.Now()

	defer func() {
		if e := recover(); e != nil {
			statsdIncrement("error")
			logInfo(0, sTime, "Error getting stat: %s", e.(error).Error())
		}
		statsdTiming(sTime, "done")
	}()

	nsInfo, err := asInfo(*cfg.aspk_node, *cfg.asinfo_port)
	if err != nil {
		logInfo(0, sTime, "Error getting node stat: %s", err.Error())
		statsdIncrement("error")
	} else {
		for nsName, nsStat := range *nsInfo {
			for key, val := range *nsStat {
				if *cfg.stdout {
					spew.Printf("%s.%s = %s\n", nsName, key, val)
				}
				if isIn(key, cfg.metric) {
					num, ok := a2i(val)
					if ok {
						statsdGauge(num, "%s.%s", nsName, key)
					}
				}
			}
		}
	}
}
Esempio n. 15
0
func dumpBloblets(dir *directory, indent int) (int, int64, int64) {
	var numBloblets int = 0
	var totalSize int64 = 0
	var minCompressedSize int64 = math.MaxInt64
	if dir.bloblet != nil {
		cr := compressedSize(dir.bloblet)
		minCompressedSize = cr
		if details {
			fmt.Printf(strings.Repeat(" ", indent))
			spew.Printf("Bloblet @ %s of size %d, compressed size %d\n", dir.bloblet.path, dir.bloblet.size, cr)
		}
		totalSize += dir.bloblet.size
		numBloblets++

	}

	for _, child := range dir.children {
		n, t, c := dumpBloblets(child, indent+2)
		numBloblets += n
		totalSize += t
		if c < minCompressedSize {
			minCompressedSize = c
		}
	}

	return numBloblets, totalSize, minCompressedSize
}
func main() {
	pings := make(chan string, 1)
	pongs := make(chan string, 1)

	ping(pings, "passed message")
	pong(pings, pongs)
	spew.Printf("%#+v\n", <-pongs)
}
Esempio n. 17
0
func main() {
	s := "sha1 this string"

	//* ハッシュの生成パターンは '''i sha1.New()'''、'''sha1.Write(bytes)'''、'''sha1.Sum([]byte{})''' です。ここでは、私達は新しいハッシュ生成から始めます。
	h := sha1.New()

	//* '''Write''' はバイトを想定しています。文字としての '''s''' を持っていたら、'''[]byte(s)''' でキャストします。
	h.Write([]byte(s))

	//* バイトスライスとなった、ファイナライズされたハッシュをこれで取得できます。'''Sum''' に渡す引数はバイトスライスに追加されますが、通常は必要ありません。
	bs := h.Sum(nil)

	//* SHA1 の値は、例えば git のコミットのように 16 進数でしばしば出力されます。~
	//* '''%x''' フォーマットを使うとハッシュの結果を 16 進数の文字列へ変換可能です。
	spew.Printf("%#+v\n", s)
	spew.Printf("%x\n", bs)
}
func main() {
	// p = fmt.Println

	//* RFC3339 に一致する定数を使って、RFC3339 に従った時刻フォーマットの例です。
	t := time.Now()
	spew.Printf("%#+v\n", t.Format(time.RFC3339))

	//* 時刻のパースは、同じレイアウト値を '''Format''' として使います。
	t1, _ := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00")
	spew.Printf("%#+v\n", t1)

	//* '''Format''' と '''Parse''' は例を基にしたレイアウトを使います。大抵は '''time''' からの定数をこれらのレイアウトのために使うことになりますが、カスタムレイアウトを使うことも可能です。
	//* レイアウトは '''Mon Jan 2 15:04:05 MST 2006''' の参照を使います。これは指定の 時刻 / 文字列をフォーマット / パースするためのパターンを示すためにです。~
	//* 例となる時刻は以下の様になっていなければいけません: 2006(年)、 15(時間)、Monday(曜日)etc.
	spew.Printf("%#+v\n", t.Format("3:04PM"))                   // t を Format() に指定した例でフォーマット。
	spew.Printf("%#+v\n", t.Format("Mon Jan _2 15:04:05 2006")) // 日にちのアンダースコアは何なのだろう?
	spew.Printf("%#+v\n", t.Format("2006-01-02T15:04:05.999999-07:00"))
	/*
	 * よくわからん。
	 * time.Parse() の第一引数はレイアウトで、第二引数が時刻っぽいが、
	 * form をいじっても望み通りのフォーマットにならない。
	 */
	form := "3 04 PM"
	t2, _ := time.Parse(form, "8 41 PM")
	spew.Printf("%#+v\n", t2)

	//* 純粋な数値表示のために、時刻値の抽出されたコンポーネントを使って標準文字フォーマットを利用することができます。
	fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())

	//* '''Parse''' は不正な入力時にパース処理の問題点を報告するエラーを返します。
	ansic := "Mon Jan _2 15:04:05 2006"
	_, err := time.Parse(ansic, "8:41PM")
	spew.Printf("%#+v\n", err)
}
Esempio n. 19
0
func main() {
	//* これはエンコード / デコードする '''string''' です。
	data := "abc123!?$*&()'-=@~'"

	//* Go は標準および URL 互換な base64 をサポートしています。これは、標準のエンコーダを使った方法です。エンコーダは '''[]byte''' を必要とするので、'''string''' をキャストします。
	sEnc := b64.StdEncoding.EncodeToString([]byte(data))
	spew.Printf("%#+v\n", sEnc)

	//* デコード時はエラーを返す場合があります。エラーを使って、適切に形成された入力値かどうかチェックすることができます。
	sDec, _ := b64.StdEncoding.DecodeString(sEnc)
	spew.Printf("%#+v\n", string(sDec))

	//* これは URL 互換な base64 フォーマットを使ったエンコード / デコードです。
	uEnc := b64.URLEncoding.EncodeToString([]byte(data))
	spew.Printf("%#+v\n", uEnc)
	uDec, _ := b64.URLEncoding.DecodeString(uEnc)
	spew.Printf("%#+v\n", string(uDec))
}
Esempio n. 20
0
func main() {
	s := new(scanner.Scanner)
	s.Init(os.Stdin)
	for {
		spew.Printf("> ")
		x := s.Scan()
		spew.Println(x, s.TokenText())
	}
}
Esempio n. 21
0
func main() {
	lex := newLex()
	lex.Init(os.Stdin)
	for {
		spew.Printf("> ")
		lex.getToken()
		spew.Println(lex.token, lex.TokenText())
	}
}
func main() {
	p := point{x: 1, y: 2}

	// 指定した値をどのようにフォーマットするか
	fmt.Printf("%v\n", p) // 構造体の値だけ

	fmt.Printf("%+v\n", p) // 構造体のフィールド名も含める

	fmt.Printf("%#v\n", p) // 構造体を Go 言語のシンタックスで表現する

	fmt.Printf("%T\n", p) // 型

	fmt.Printf("%t\n", true) // boolean

	fmt.Printf("%d\n", 123) // 整数

	fmt.Printf("%b\n", 14) // 2 進数

	fmt.Printf("%c\n", 33) // Unicode ポイントに一致する文字

	fmt.Printf("%x\n", 456) // 16 進数

	fmt.Printf("%f\n", 78.9) // 小数点

	fmt.Printf("%e\n", 1234000000.0) // 科学的記数法
	fmt.Printf("%E\n", 1234000000.0) // 科学的記数法

	fmt.Printf("%s\n", "\"string\"") // 文字列

	fmt.Printf("%q\n", "\"string\"") // クォート処理済み文字列

	fmt.Printf("%\n", "hex this") // 各バイトを 2 文字の 16 進数文字列として

	fmt.Printf("%p\n", &p) // ポインタ

	fmt.Printf("|%6d|%6d|\n", 12, 345) //整数の桁合わせ(デフォルトは右詰め)

	fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // 少数の桁合わせ(デフォルトは右詰め)

	fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // 左寄せ

	fmt.Printf("|%6s|%6s|\n", "foo", "b") // 文字の桁 (?) 合わせ(デフォルトは右詰め)

	fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // 左寄せ

	/* おまけ */
	// go-spew パッケージの便利なことよ。
	spew.Printf("%#+v\n", p)
	// あら、Dump なんてあるの。
	spew.Dump(p)

	s := fmt.Sprintf("a %s", "string") // フォーマット化した文字列を返す
	fmt.Println(s)

	fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
Esempio n. 23
0
func main() {
	spew.Printf("%d, %x, %o, %b\n", 100, 100, 100, 100)

	fmt.Printf("[%d]\n", 10)
	fmt.Printf("[%4d]\n", 10)     // 4 桁表示の右詰め。
	fmt.Printf("[%4d]\n", 100000) // 桁が多すぎる場合はオプションは無視される。
	fmt.Printf("[%4d]\n", 123456)
	fmt.Printf("[%-8d]\n", 123456) // - で左詰め。
	fmt.Printf("[%08d]\n", 123456) // 0 でゼロ埋め。
}
Esempio n. 24
0
func main() {
	var state = make(map[int]int)
	var mutex = &sync.Mutex{}
	var ops int64 = 0

	for r := 0; r < 100; r++ {
		go func() {
			total := 0
			for {
				key := rand.Intn(5)
				mutex.Lock()
				total += state[key]
				mutex.Unlock()
				atomic.AddInt64(&ops, 1)
				runtime.Gosched()
			}
		}()
	}

	for w := 0; w < 10; w++ {
		go func() {
			for {
				key := rand.Intn(5)
				val := rand.Intn(100)
				mutex.Lock()
				state[key] = val
				mutex.Unlock()
				atomic.AddInt64(&ops, 1)
				runtime.Gosched()
			}
		}()
	}

	time.Sleep(time.Second)

	opsFinal := atomic.LoadInt64(&ops)
	spew.Printf("ops: %#+v\n", opsFinal)
	mutex.Lock()
	spew.Printf("state: %#+v\n", state)
	mutex.Unlock()
}
Esempio n. 25
0
func main() {
	//* この '''64''' は何 bit の精度で使ってパースするかを '''Parsefloat''' に伝えます。
	f, _ := strconv.ParseFloat("1.234", 64)
	spew.Printf("%#+v\n", f)

	//* '''ParseInt''' の '''0''' は文字列から基数を推論することを意味します。'''64''' は結果を 64 bit に合わせるために必要です。
	i, _ := strconv.ParseInt("123", 0, 64)
	spew.Printf("%#+v\n", i)

	//* '''ParseInt''' は 16 進数の数値も認識します。
	d, _ := strconv.ParseInt("0x1c8", 0, 64)
	spew.Printf("%#+v\n", d)

	//* '''PerseUint''' も使えます。
	u, _ := strconv.ParseUint("789", 0, 64)
	spew.Printf("%#+v\n", u)

	//* '''Atoi''' は 10 進数 '''int''' にパースする便利な関数です。
	k, _ := strconv.Atoi("135")
	spew.Printf("%#+v\n", k)

	//* パース関数は不正な入力時にエラーを返します。
	_, e := strconv.Atoi("wat")
	spew.Printf("%#+v\n", e)
}
func main() {
	done := make(chan bool, 1)
	// ぶっちゃけこうでもいいけど本質とはずれているな。
	// done := make(chan bool)

	// チャネルってポインタなのか?これはいわゆる値渡し?参照渡し?
	go worker(done)

	<-done

	/* おまけ */
	// チャネルってなんだ。
	spew.Printf("\n--- omake ---\n")
	var i int
	var null_c chan int
	null_c = make(chan int)
	c := make(chan int)

	spew.Printf("i: %#+v\n", i)
	// ポインタかな。
	spew.Printf("null_c: %#+v\n", null_c)
	spew.Printf("c: %#+v\n", c)
	spew.Printf("&null_c: %#+v\n", &null_c)
	spew.Printf("&c: %#+v\n", &c)

	// 値渡しな様子。
	// あるアドレスを指し示すチャネルのコピーが作られるっぽ。
	f(c)
}
Esempio n. 27
0
// This example demonstrates how to use Printf to display a variable with a
// format string and inline formatting.
func ExamplePrintf() {
	// Create a double pointer to a uint 8.
	ui8 := uint8(5)
	pui8 := &ui8
	ppui8 := &pui8

	// Create a circular data type.
	type circular struct {
		ui8 uint8
		c   *circular
	}
	c := circular{ui8: 1}
	c.c = &c

	// Print!
	spew.Printf("ppui8: %v\n", ppui8)
	spew.Printf("circular: %v\n", c)

	// Output:
	// ppui8: <**>5
	// circular: {1 <*>{1 <*><shown>}}
}
Esempio n. 28
0
func main() {
	c1 := make(chan string)
	c2 := make(chan string)

	go func() {
		time.Sleep(time.Second * 2)
		c1 <- "one"
	}()
	go func() {
		time.Sleep(time.Second * 1)
		c1 <- "two"
	}()

	for i := 0; i < 2; i++ {
		select {
		case msg1 := <-c1:
			spew.Printf("received: %#+v\n", msg1)
		case msg2 := <-c2:
			spew.Printf("received: %#+v\n", msg2)
		}
	}
}
Esempio n. 29
0
func main() {
	ticker := time.NewTicker(time.Millisecond * 500)
	spew.Printf("%#+v\n", ticker)
	go func() {
		for t := range ticker.C {
			// チャネルには tick した時の時刻が入っている。
			fmt.Println("Tick at", t)
		}
	}()

	time.Sleep(time.Millisecond * 1500)
	ticker.Stop()
	fmt.Println("Tick stopped")
}
Esempio n. 30
0
func getVersion() {
	home := os.Getenv("HOME")
	inf, err := ioutil.ReadFile(home + "/Steam/steamapps/common/dota 2 beta/dota/steam.inf")
	if err != nil {
		panic(err)
	}

	steamInf := map[string]string{}
	for _, match := range infMatch.FindAllStringSubmatch(string(inf), -1) {
		steamInf[match[1]] = match[2]
	}

	spew.Printf("Client %s Patch %s\n", steamInf["ClientVersion"], steamInf["PatchVersion"])
}