Go中 struct{} 和 struct{}{}区别

学习博客:https://www.cnblogs.com/show58/p/12655375.html

struct是Go中的关键字,用于定义结构类型。

type User struct {
    Name string
    Age  int
}

struct {} :表示struct类型
struct {}是一种普通数据类型,一个无元素的结构体类型,通常在没有信息存储时使用。
优点是大小为0,不需要内存来存储struct {}类型的值。

struct {} {}:表示struct类型的值,该值也是空。
struct {} {}是一个复合字面量,它构造了一个struct {}类型的值,该值也是空。

var set map[string]struct{}
set = make(map[string]struct{})

// Add some values to the set:
set["red"] = struct{}{}
set["blue"] = struct{}{}

// Check if a value is in the map:
_, ok := set["red"]
fmt.Println("Is red in the map?", ok)
_, ok = set["green"]
fmt.Println("Is green in the map?", ok)

输出内容

Is red in the map? true
Is green in the map? false

通常struct{}类型channel的用法是使用同步,
一般不需要往channel里面写数据,只有读等待,而读等待会在channel被关闭的时候返回。

借鉴博客:https://www.cnblogs.com/show58/p/12655396.html

package main

import (
    "time"
    "log"
)

var ch chan struct{} = make(chan struct{})

func foo() {
    log.Println("foo start");
    time.Sleep(3 * time.Second)
    log.Println("foo close chan");
    close(ch)
    log.Println("foo end");
}

func main() {
    log.Println("main start");
    go foo()
    log.Println("main wait chan");
    <-ch
    log.Println("main end");
}

结果:

2021/11/07 11:19:47 main start
2021/11/07 11:19:47 main wait chan
2021/11/07 11:19:47 foo start
2021/11/07 11:19:50 foo close chan
2021/11/07 11:19:50 foo end
2021/11/07 11:19:50 main end

如果一开始就往 元素类型为 struct{} 的 chan 中写元素
则 main 中会立马收到信息

package main

import (
    "time"
    "log"
)

var ch chan struct{} = make(chan struct{})

func foo() {
    log.Println("foo start");
    ch <- struct{}{}
    time.Sleep(3 * time.Second)
    log.Println("foo close chan");
    close(ch)
    log.Println("foo end");
}

func main() {
    log.Println("main start");
    go foo()
    log.Println("main wait chan");
    ret, ok := <-ch
    if ok {
        log.Println("main recv info : ", ret);
    } else {
        log.Println("main chan has closed");
    }

    log.Println("main end");
}

读到的数据为空

おすすめ

転載: blog.csdn.net/wangkai6666/article/details/121189325