LoginSignup
0
0

【Go言語学習】struct{}{}

Posted at

struct{}{}

再度、なんだこりゃと思い

以前、関数の引数の定義において c <-chan struct{} という表現を知った時、メモリを消費しない表現であると認識したが、受信専用で有ったためか struct{}{} は出てこなかったようで...
マップや送信専用チャネルの変数に入れる際は c chan<- struct{}{} とするようで、
意味としては struct{}型の空のインスタンス(値が何も無いので、値を管理するためのメモリを消費しない) を表現しているとのこと。
・インスタンス自体は存在するためnilではない
・配列のノリで struct{}{}{} をやると、文法エラー
・interface{}{}も文法エラー

mapで試す

package main

import "fmt"

func main() {
	set := make(map[string]interface{})

	// 要素を追加
	set["item1"] = struct{}{}
	set["item2"] = ""
	set["item3"] = nil

	// 要素が存在するか確認
	if v, ok := set["item1"]; ok {
		if v == nil {
			fmt.Println("item1 exists and is nil")
		} else {
			fmt.Println("item1 exists and is not nil")
		}
	} else {
		fmt.Println("item1 does not exist")
	}

	if v, ok := set["item2"]; ok {
		if v == nil {
			fmt.Println("item2 exists and is nil")
		} else {
			fmt.Println("item2 exists and is not nil")
		}
	} else {
		fmt.Println("item2 does not exist")
	}

	if v, ok := set["item3"]; ok {
		if v == nil {
			fmt.Println("item3 exists and is nil")
		} else {
			fmt.Println("item3 exists and is not nil")
		}
	} else {
		fmt.Println("item3 does not exist")
	}
}
item1 exists and is not nil
item2 exists and is not nil
item3 exists and is nil
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