V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yellowmarlboro
V2EX  ›  Go 编程语言

如何在 golang 里的 map 的同一个 key 放不同的 struct?

  •  
  •   yellowmarlboro · 2021-03-11 19:30:01 +08:00 · 1674 次点击
    这是一个创建于 1147 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package learn
    
    type A struct {
    
    }
    
    type B struct {
    
    }
    
    type Tasks struct {
    	Name string
    	ToSt Te
    }
    
    type Te interface{
    	Tes()
    }
    
    func (s *A)Tes() {
    }
    
    func (s *B)Tes() {
    }
    
    func TT() {
    	var1 := Tasks{Name: "s", ToSt: A{}}
    }
    
    • 想让 Task 的 ToSt 指向 A 或者 B 的一个 struct 。想这么做,但是很明显不行。
    8 条回复    2021-03-12 15:21:17 +08:00
    rrfeng
        1
    rrfeng  
       2021-03-11 19:34:50 +08:00
    首先你这也不是 map 呀

    可以用 interface,不过不要用空 interface
    rekulas
        2
    rekulas  
       2021-03-11 19:37:31 +08:00
    ToSt 改成 interface 不就可以么
    lewinlan
        3
    lewinlan  
       2021-03-11 22:21:41 +08:00   ❤️ 4
    &A{}即可。
    因为 A 没有实现接口,*A 实现了。
    unixeno
        4
    unixeno  
       2021-03-11 22:23:00 +08:00 via Android
    map[string]interface{}
    yrj
        5
    yrj  
       2021-03-12 04:07:36 +08:00 via iPad
    三楼正解
    ly020044
        6
    ly020044  
       2021-03-12 08:17:13 +08:00
    3 楼没毛病,因为你 A, B 都是用指针对象实现的接口
    sherlockwhite
        7
    sherlockwhite  
       2021-03-12 15:20:43 +08:00
    package main

    type A struct {

    }

    type B struct {

    }

    type Te interface{
    Tes()
    }

    type Tasks struct {
    Name string
    ToSt Te
    }

    func (s *A) Tes() {

    }

    func (s *B) Tes() {
    }

    func TT() {
    var test A
    var1 := Tasks{Name: "s", ToSt: &test}
    }
    sherlockwhite
        8
    sherlockwhite  
       2021-03-12 15:21:17 +08:00
    3 楼正解
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1832 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:57 · PVG 08:57 · LAX 17:57 · JFK 20:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.