LoginSignup
0
0

【Go言語】データ型の拡張

Posted at

Goでは、intstringなどの組み込み型スライスmapなどの複合型を拡張して新しい型を作成することが可能。

新しい型を定義する際、元となる型を「基底型(underlying type)」と呼ぶ。
新しい型を作ることで、基底型の特性を引き継ぎつつ新しいメソッドを追加することができる。

メソッドを追加する

int型を基底型としてHTTPStatus型を定義し、String()メソッドを追加する

package main

import (
	"fmt"
)

// HTTPStatus型の定義
type HTTPStatus int

// HTTPStatusの定数
const (
	StatusOK              HTTPStatus = 200
	StatusUnauthorized    HTTPStatus = 401
	StatusPaymentRequired HTTPStatus = 402
	StatusForbidden       HTTPStatus = 403
)

// HTTPStatus型にString()メソッドを追加
func (s HTTPStatus) String() string {
	switch s {
	case StatusOK:
		return "OK"
	case StatusUnauthorized:
		return "Unauthorized"
	case StatusPaymentRequired:
		return "Payment Required"
	case StatusForbidden:
		return "Forbidden"
	default:
		return fmt.Sprintf("HTTPStatus(%d)", s)
	}
}

func main() {
	// HTTPStatus型の使用例
	status := StatusOK
	fmt.Println("HTTP Status:", status, status.String())
}

拡張した組み込み型で、基底型の挙動を利用する

拡張された型は、元の基底型の機能も利用できる。
例えば、mapを基底型とするurl.Values型は、mapの機能に加えて特有のメソッドを持っている。

package main

import (
	"fmt"
	"net/url"
)

func main() {
	// url.Values型のインスタンスを作成
	values := url.Values{}

	// 値を追加
	values.Add("key1", "value1")
	values.Add("key2", "value2")

	// 値を出力
	for key, value := range values {
		fmt.Printf("%s: %v\n", key, value)
	}
}

ファクトリー関数の提供

型をより使いやすくするために、ファクトリー関数を提供することが推奨されている。
これにより、型のインスタンス化を簡単にし、エラーチェックを組み込むことが可能になる。

package main

import (
	"errors"
	"fmt"
)

// MyType はカスタムデータ型です。
type MyType struct {
	Value string
}

// NewMyType は MyType の新しいインスタンスを作成するファクトリー関数です。
// この関数はエラーチェックを含めることもできます。
func NewMyType(value string) (*MyType, error) {
	if value == "" {
		return nil, errors.New("value cannot be empty")
	}
	return &MyType{Value: value}, nil
}

func main() {
	// ファクトリー関数を使用して MyType のインスタンスを作成
	myInstance, err := NewMyType("Hello, World!")
	if err != nil {
		fmt.Println("Error creating MyType instance:", err)
		return
	}

	// インスタンスの使用
	fmt.Println("MyType Value:", myInstance.Value)
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0