Skip to content

Instantly share code, notes, and snippets.

@ymotongpoo
Last active September 6, 2020 07:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymotongpoo/f6533f5e16a185f348d92f2d4c9b2f05 to your computer and use it in GitHub Desktop.
Save ymotongpoo/f6533f5e16a185f348d92f2d4c9b2f05 to your computer and use it in GitHub Desktop.
golang.org/x/text/message sample
module gist.github.com/f6533f5e16a185f348d92f2d4c9b2f05
require golang.org/x/text v0.3.0
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
// Copyright 2018 Yoshi Yamaguchi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"time"
"golang.org/x/text/currency"
_ "golang.org/x/text/feature/plural"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func init() {
message.SetString(language.Japanese, "%d days to the new year day.\n",
"新年まであと%d日\n")
// NOTE: 複数形なら message.Set と plural.Selectf うまく選択できるはずが
// 次のコードはかならずotherにルーティングされてしまう。
// message.Set(language.Japanese, "%d days to the new year day.\n",
// plural.Selectf(1, "%d",
// "=1", "明日は元日\n",
// "other", "新年まであと%d日\n",
// ))
message.SetString(language.Japanese, "%s, I wish you a happy new year.\n",
"%s、良いお年を\n")
// フォーマット引数の順番を入れ替える場合には"[]"を使って指定する
message.SetString(language.Japanese, "%s, %s\n", "%[2]s、%[1]s\n")
}
func localization() {
jp := language.Japanese
p := message.NewPrinter(jp)
cur, _ := currency.FromTag(jp)
// クリスマスには¥ 120000のiPadを買いました。(カンマ区切りが反映されない)
p.Printf("クリスマスには%dのiPadを買いました。\n", currency.NarrowSymbol(cur.Amount(120000.0)))
// お年玉は10,000円あげるつもりです。(カンマ区切りが反映されている)
p.Printf("お年玉は%d円あげるつもりです。\n", 10000)
}
func translation() {
p := message.NewPrinter(language.Japanese)
local, _ := time.LoadLocation("Local")
nyd := time.Date(2019, 1, 1, 0, 0, 0, 0, local)
days := nyd.Sub(time.Now()) / (time.Hour * 24)
// 新年まであと6日
p.Printf("%d days to the new year day.\n", days)
// みなさん、良いお年を
p.Printf("%s, I wish you a happy new year.\n", "みなさん")
// 世界、こんにちは
p.Printf("%s, %s\n", "こんにちは", "世界")
}
func main() {
localization()
translation()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment