c4se記:さっちゃんですよ☆

.。oO(さっちゃんですよヾ(〃l _ l)ノ゙☆)

.。oO(此のblogは、主に音樂考察Programming に分類されますよ。ヾ(〃l _ l)ノ゙♬♪♡)

音樂は SoundCloud に公開中です。

考察は現在は主に Scrapbox で公表中です。

Programming は GitHub で開發中です。

#golang §43 Exercise: Maps

A Tour of Go chapter 43

Exercise: Maps

Implement WordCount. It should return a map of the counts of each “word” in the string s. The wc.Test function runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.

Example

package main

import (
	"code.google.com/p/go-tour/wc"
	"strings"
)

func WordCount(s string) map[string]int {
	words := make(map[string]int)
	for _, word := range strings.Fields(s) {
		words[word] += 1
	}
	return words
}

func main() {
	wc.Test(WordCount)
}

付言

strings.Fields(s string) []stringは、文字列を与えると、その文字列の空白文字で区切ったスライスを、或いは空のスライスを返す。JavaScriptで言えば

"   SOME  STRINGS   ".trim().split(/ +/)

と同じ。スライス (slice) とは配列の様なものである。#golang §44 Exercise: Slicesではスライスがテーマである。
words[word] = 0の如き初期化は不要である。