Go関連のことを調べてみた2020年03月16日

Go関連のことを調べてみた2020年03月16日
目次

Go 言語でトランプのStructを作って、カードを強い順に並び替える ( #go lang sort card Struct )

“`go
package main

import (
“fmt”
“sort”
)

type Card struct {
Strong int
Name string
}

func main() {
cards := []Card{
Card{2, “2”},
Card{3, “3”},
Card{4, “4”},
Card{5, “5”},
Card{6, “6”},
Card{7, “7”},
Card{8, “8”},
Card{9, “9”},
Card{10, “10”},
Card{11, “J”},
Card{12, “Q”},
Card{13, “K”},
Card{14, “A”},
}

sort.SliceStable(cards, func(i, j int) bool {
return cards[i].Strong > cards[j].Strong
})

fmt.Println(cards)
}

// [{14 A} {13 K} {12 Q} {11 J} {10

元記事を表示

#Go 言語でシャッフルした52枚のトランプを1枚ずつ配るサンプル ( Go lang deal shuffle playing cards example )

“`golang
package main

import (
“fmt”
“math/rand”
“time”
)

func main() {
cards := generateCards()

shuffleCards(cards)

yourCards := []string{}

for _, card := range cards {
yourCards = append(yourCards, card)
fmt.Println(“Your cards are …”)
fmt.Println(yourCards)
}
}

func generateCards() []string {
cardSeeds := []string{“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”, “A”}
cards := []string{}

for i := 0; i < 4; i++ { cards = append(cards, cardSeeds...) } r

元記事を表示

Go 言語で “declared but not used” のエラーを無効にするには 未使用変数をアンダースコアだけにすれば良いじゃない ( #go lang ignore ))

“`go
package main

import (
“fmt”
)

func main() {
cards := []string{“A”, “K”, “Q”, “J”}

for _, card := range cards {
fmt.Println(card)
}

// i declared but not used
// for i, card := range cards {
// fmt.Println(card)
// }

}

“`

`_i` とかじゃなくアンダースコアだけ `_` にすると良さげ

# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3029

元記事を表示

Go 言語で無限ループしながら コンソールのユーザー入力を待ち受ける ( #Go wait user input in console with infinite loop )

“`go

package main

import (
“bufio”
“fmt”
“os”
)

func main() {
for {
fmt.Println(“Enter some words!”)
input := bufio.NewScanner(os.Stdin)
input.Scan()
fmt.Println(“input is ” + input.Text())
}
}

// Enter some words!
// A
// input is A
// Enter some words!
// B
// input is B
// Enter some words!
// C
// input is C
// Enter some words!

“`

# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3028

元記事を表示

go.modってどこにおくのがいいのだろう

#go.modってどこにおくのがいいのか

先日一からgoでサービスを作っていたのですが、go.modの置き場で迷ってしまい少し時間を無駄遣いした時に、意外と日本語の情報がなかったので残そうと思います。

#結論:ルートディレクトリに置く

 結論からいうと、プロジェクトのルートディレクトリにおくのが正解でした。
go modはもともと業務でも使っていたのである程度知識はあると思っていたのですが、いざ自分で初めから作るとなるとどこで `go mod init` するんだ?ってなってしまいました。勉強不足です。色々とググってみたのですが、あまりgo.modをおく場所に関する情報はなくて、自分で色々いじってみてなんとか解決しました。
 解決した後に1次ソースには当たっていなかったので(まず当たれという話ですが、、)1次ソースをみてみるとそう行った記述がありました。

“`
A module is a collection of Go packages stored in a file tree with a go.mod file at its root.
“`

ざっくり訳すと

元記事を表示

Go 言語でスライスの要素をすべて展開して、インデックスの順序と値を出力する例 ( #go foreach slice all elements )

“`golang
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
)

func main() {

cards := []string{“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”, “A”}
for i, card := range cards {
fmt.Println(i, card)
}

}

// e.g
//
// 0 2
// 1 3
// 2 4
// 3 5
// 4 6
// 5 7
// 6 8
// 7 9
// 8 10
// 9 J
// 10 Q
// 11 K
// 12 A

“`

# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3027

元記事を表示

Go 言語でスライス/配列をランダムな順番でシャッフルっする ( #go shuffle array / slice / cards example )

“`golang
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
“math/rand”
“time”
)

func main() {
cards := []string{“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”, “A”}
cards4 := []string{}

for i := 0; i < 4; i++ { cards4 = append(cards4, cards...) } rand.Seed(time.Now().UnixNano()) rand.Shuffle(len(cards4), func(i, j int) { cards4[i], cards4[j] = cards4[j], cards4[i] }) fmt.Println(cards4) // [7 3 10 7 10 9 A 8 K 9 J 10 10 A K Q K 5 K Q 6 J 3 8 2 6 2

元記事を表示

Go 言語で配列(Slice)からランダムに文字列を選ぶ ( #go random select string in slice )

“`golang
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
“math/rand”
“time”
)

func main() {
cards := []string{“A”, “B”, “C”}

rand.Seed(time.Now().UnixNano())

for i := 0; i < 10; i++ { num := rand.Intn(len(cards)) fmt.Println(cards[num]) } } // result // e.g // C // C // C // C // C // B // B // C // B // C ``` # Original by Github issue https://github.com/YumaInaura/YumaInaura/issues/3024

元記事を表示

Go 言語で スライスを合体させてトランプの組み合わせを作る ( #go join multiple string slice n times )

“`go
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
)

func main() {
cards := []string{“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”, “A”}
cards4 := []string{}

for i := 0; i < 4; i++ { cards4 = append(cards4, cards...) } fmt.Println(len(cards4)) // 52 fmt.Println(cards4) // [2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A] } ``` # Original by Github issue https://github.com/YumaInaur

元記事を表示

Go lang / rand.Seed(time.Now().UnixNano()) used as value / #go

“`go
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
“math/rand”
“time”
)

func main() {
// NG
seed_result := rand.Seed(time.Now().UnixNano())

// OK
// Seed does not need return value
// rand.Seed(time.Now().UnixNano())

fmt.Println(rand.Int())
}
“`

Seed生成した値を使い回すのではなく、一回だけ設定すれば良いみたいだ。なので帰り値は要らない。

# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3022

元記事を表示

Go lang で1桁のランダムな数値を生成する / rand.Intn(9) / #go

“`golang
// https://golang.org/pkg/math/rand/

package main

import (
“fmt”
“math/rand”
“time”
)

func main() {
rand.Seed(time.Now().UnixNano())

for i := 0; i < 100; i++ { fmt.Println(rand.Intn(9)) // e.g exclude zero // fmt.Println(1 + rand.Intn(9-1)) } } // Result example // // 2 // 7 // 1 // 0 // 2 // 8 // 3 // 1 // 2 // 4 // 3 // 3 // 3 // 4 // 4 // 7 // 3 // 2 // 6 // 7 // 2 // 4 // 1 // 4 // 4 // 2 // 1 // 2 // 1 // 7 // 1 // 0 // 8 // 1 // 4 //

元記事を表示

【Go】ポインタ

#### ポインタ


値渡し、ポインタ渡し、参照渡しの違いについて
基本こちらの記事で理解
[参照リンク](https://qiita.com/lon9/items/e70e3b453cb485858062)

#### 自分なりの整理


“`Go:
# このポインタ型の関数は
# アドレス値を受け取る
# 自身のアドレス値も別に持ってる(“&”でアドレス確認可)
# 受け取ったアドレス値にあるデータにアクセス(”*”)

func pointer(i *int){
fmt.Println(“値(受け取ったアドレス)=メイン(アドレス)が入る: “, i)
fmt.Println(“自身のアドレス: “, &i)
fmt.Println(“値(受け取ったアドレス)のデータにアクセス: “, *i)
}

# メイン
func main() {
i := 10
fmt.Println(“メイン(値): “, i)
fmt.Println(“メイン(アドレス): “, &i)

# ポインタ型の関数にはア

元記事を表示

【Go】Mac + VSCode + Go 環境設定

### Goのインストール


基本こちらに記載されていた手順でインストール
[参考リンク](https://qiita.com/oruharo/items/545378eae5c707f717ed)

### 【エラー対応諸々】


#### ① Go:Install/Update Tools が FAILED になる [(スクショないので参考画面)](https://github.com/microsoft/vscode-go/issues/2724)

→以前GoLand(IDE)で旧バージョン(v1.11)を利用していたため。
→旧バージョンを削除し新バージョン(v1.13)をインストール [(アップグレードの手順参考)](https://www.quora.com/Whats-the-easiest-way-to-update-Go-programming-language-to-the-latest-version-in-Linux)
(旧バージョンのアンインストールは /usr/local/go 消したら良いよう)

→アップグレード後、FAILEDなくす

元記事を表示

【Golang】Go 1.14での独自パッケージimportでエラーになるとき

数年Goを離れてたら、バージョン1.14になってたのでキャッチアップしなければ(Go 1.10の人)。
`go mod`による管理が楽しい。

## TL;DR

– 各ディレクトリにgo.modを設置
– `go mod init`をする
– local importするため各go.modファイルに`replace`を追加
– 参照階層がネストするときに注意
– 例)main.go → ./api.go → ./domain/models/Sample.go
– mainのgo.modにはreplace文が2行必要になります
– main.goから見たapiの相対パス
– main.goから見たmodelsの相対パス

## 出てきて困ったエラー

“`
C:\Users\username\go\src\github.com\username\repo>go build ./…
go: finding module for package github.com/username/repo/domain/model

元記事を表示

interface をなるべく変更しないように gorm を使う

## 背景

clean architectureでアプリケーションを作っていると db とのデータのやりとりは抽象化しておくことが多いと思います。そのときに定義する interface が findUserByXXX, findByUserZZZ だと他のデータの取り出し方をしたいと思った時に interface を新規に追加しないといけません。メソッドを分けたとしても、似たようなコードがその中に書かれ、コードベースは肥大化していきます。
そこで、クエリビルダっぽいものを作ってなるべくデータの取り出し方を抽象化したメソッド内部でやるのではなく、クエリビルダに任せたいと思いました。
試作的に書いたのでまだ考慮は必要なのですが、簡単なCRUDアプリケーションのときには十分使えそうなので自ら使って改良を加えて行きたいです。

## 内容

db とのやり取りを Repository を使って実装します。
Repository は Query struct を受け取り、struct に設定された条件をデータ取得時に組み立て、クエリを実行します。そのため、Query struct はビジネスロ

元記事を表示

Golangでwebアップローダーを作る

とりあえず作成したので、アップロード
https://github.com/karosuwindam/goupload

重要部分を抜き出し
アップロードの関数部分

“`go:upload.go
package main
import (
“fmt”
“net/http”
“os”

)

const UPLOAD = “upload”

func upload(w http.ResponseWriter, r *http.Request) {
var data []byte = make([]byte, 1024)
var tmplength int64 = 0
var output string
urldata := “”
searchdata := “”
if r.Method == “POST” {
file, fileHeader, e := r.FormFile(“file”)
if e != nil {
fmt.Fprintf(w, “アップロードに失敗しました。”)
return
}
writefilename := f

元記事を表示

「Azure SDK for Go」とは?

Azure SDK for Goは、マイクロソフト社のパブリッククラウド「[Azure](https://azure.microsoft.com/ja-jp/)」をGoでコーディングして扱うためのSDK(ソフトウェア開発キット)です。

Apache License 2.0ライセンスのオープンソースソフトウェアであり、GitHub上で管理および開発されています。

– [GitHub – Azure/azure-sdk-for-go: Microsoft Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go)

最初のコミットは2014年8月11日で、2016年、2017年とベータ期間を経て、2018年2月12日のv14.0.0で正式リリースとなりました。

– [Build Go apps for Azure with the Go SDK, now generally available | Azure のブログと更新プログラム | Microsoft Azure](https://azure.microsoft.c

元記事を表示

コマンドラインから文字列の取得

# 初めに
Atcoderの文字列取得の定石を貼ります。

#コマンドラインから複数行一度に取得

“`go
package main

import(
“fmt”
“bufio”
“stdin”
)

func main(){
lines := getStdin()
for k,v := range lines{
fmt.Printf(“line[%s]=%s\n”,k,v)
}

}

func getStdin() []string {
stdin := bufio.NewScanner(os.Stdin)
lines := []string{}
for stdin.Scan() {
if err := stdin.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
lines = append(lines, stdin.Text())
}
return lines
}
“`

実行結果

“`terminal
$go run sample.go
a b

元記事を表示

AWSを用いたGoの開発環境構築でWindowsユーザがMacユーザに歩み寄るナレッジをまとめた

# はじめに

チームの開発環境の構築手順って、みなさまどうしていますか?多くのチームはリポジトリ内のREADMEや、チームWikiに準備することが多いのではないでしょうか?

その際、そのリポジトリ固有のBuild & Deploy & Release手順は記載することは普通だと思いますが、ここで問題になるのは、開発者の環境がWindows, Macなどで割れている場合です。全員Windows or Macで揃えろよってことですが、今の自分のチームはMac:Windows=7:3くらいです。ハードやライセンスの問題から自分たちと同じ用に完全に開発環境を揃えるのも難しいチームも多いでしょう。Amazon Workspacesは一つの解には間違いないですが、なるべく既存の資産を有効活用したいPJも多いと思います。

私のチームの話ですがWindowsは参画したてのメンバーや、アルバイトer社員の方が多く、事実上スキルが低いメンバーが多いのですが、環境構築手順がMacに比重高めなので脳内翻訳が大変な場合があります。

ここではなるべくWindowsユーザがMacユーザ用に書かれた環境構築手

元記事を表示

[golang]rake db:migrateみたいな事をgoでできるgooseを使ってみた

Go言語でマイグレーションどうやんの…というところで色々試したうちの1つ。
Railsの`rake db:migration`みたいな事ができるので、Railsに慣れている人には比較的使いやすいのではないかと思う。

– [pressly/goose: Goose database migration tool – fork of https://bitbucket.org/liamstask/goose](https://github.com/pressly/goose)

## 環境

go 1.13.4

## gooseが記事執筆時点で対応しているデータベース

– postgres
– mysql
– sqlite3
– mssql
– redshift

## gooseのインストール

“`sh
go get -u github.com/pressly/goose/cmd/goose
“`

## 各種コマンド

### databaseを作る

db:create相当のコマンドは無い

### マイグレーションファイルを作る

“`sh
$ goose mysql

元記事を表示

OTHERカテゴリの最新記事