コンストラクタの慣例
Coddyの「C開発者のためのGo」コースのレッスン 28/48。
Cでの初期化では、APIが依存するすべての状態フィールドを設定する必要があります。Goはゼロ値を提供しますが、確保されたゼロ値の構造体でもドメイン不変条件に違反する場合があります。ファクトリー関数で入力を検証できます。あるオブジェクトが別のオブジェクトに影響を与えてはならない場合は、インスタンスごとに変更可能なコレクションを確保してください。
Goには特別なコンストラクター構文がありません。NewType関数は慣例であり、エラーを返す場合もあります。無効な状態が戻り値に含まれないようにしてください。ポインターを返すと共有された同一性を提供でき、小さな不変レコードには値を返すのが適切な場合があります。
Cの例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Score { int points; };
struct Score make_score(int points) { struct Score s = {points}; return s; }
int main(void) {
struct Score a = make_score(4); struct Score b = make_score(0);
a.points += 3;
printf("%d %d\n", a.points, b.points);
return 0;
}ソースコードの出力:
7 0Goの例
package main
import ("fmt")
type Greeting struct { Text string }; func NewGreeting(name string) Greeting { return Greeting{Text:"Hello "+name} }
func main(){p:=NewGreeting("Ada")
fmt.Println(p.Text)}Goの出力:
Hello Adaチャレンジ
簡単NewAccount(balance int) (*Account,error) を実装してください。負の残高の場合は nil と nil ではないエラーを返し、それ以外の残高の場合は Balance() がその値と一致するアカウントを返します。入力は残高を1つです。
宣言された API を実装し、結果を出力せずに返してください。ドライバーは必要な API を確認し、呼び出し元の入力を保持します。コレクションの標準出力には JSON ではなく、Go の角括弧形式が使われます。
コードは account.go と exercise.go に記述します。main.go には用意された入出力コードがあり、編集できません。フラットな package main を1つだけ使い、2つ目の main を追加しないでください。
自分で試してみよう
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
a,e:=NewAccount(7); must(e==nil && a!=nil && a.Balance()==7,"constructor API"); a,e=NewAccount(-1); must(a==nil && e!=nil,"constructor rejection");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのGoのすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ