go - 内部循环定义父链接

标签 go

我想循环我的表名以添加由符号“_”定义的关联。

如果表 a_ba 那么 b 存在那么 a = [b], b = [a]。 最后,我不必打印名称中包含“_”的表

结构

// Table with Fields and Assoc
type Table struct {
    Name       string
    Assoc      []Assoc
}

// Assoc is a name of associated Table
type Assoc struct {
  Name string
}
tables := []string{
    "a",
    "b",
    "c",
    "d",
    "f",
    "a_b",
    "a_c",
    "a_d_f",
    "c_d",      
}

var tbls []Table

for _, t := range tables {
    if strings.Contains(t, "_") {
        // Split to find "_" like assoc := strings.Split(t, "_") ?
        // append in struct "Table{Name:a, Assoc:  [b,c,d,f]}"
        // append in struct "Table{Name:b, Assoc:  [a]}"
        // append in struct "Table{Name:c, Assoc:  [a,d]}"
        // append in struct "Table{Name:d, Assoc:  [a,c,f]}"
        // append in struct "Table{Name:f, Assoc:  [a,d]}"      
    } else {
        n := Table{
            Name: t,
        }
        tbls = append(tbls, n)
    }

}

fmt.Println(tbls) 一样返回:

[{a [b,c,d,f]} {b [a]} {c [a,d]} {d [a,c,f]} {f [a,d]}]

Go Playground

最佳答案

使用 map 完成上面提到的 https://play.golang.org/p/8C5M0L-es6o

package main

import (
    "fmt"
    "strings"
)

// Table with Fields and Assoc
type Table struct {
    Name  string
    Assoc map[string]int
}

// Assoc is a name of associated Table
// type Assoc struct {
//  Name string
// }

func main() {
    tables := []string{
        "a",
        "b",
        "c",
        "d",
        "f",
        "a_b",
        "a_c",
        "a_d_f",
        "c_d",
    }

    var tbls = make(map[string]map[string]int)

    for _, t := range tables {
        if strings.Contains(t, "_") {
            splitAssocs := strings.Split(t, "_")            
            for i:=0;i<=len(splitAssocs)-2;i++ {
                for j:=(i+1);j<=len(splitAssocs)-1;j++{
                    _, ok := tbls[splitAssocs[i]]
                    if !ok{
                        tbls[splitAssocs[i]] = make(map[string]int)
                    }
                     _, ok = tbls[splitAssocs[j]]
                    if !ok{
                        tbls[splitAssocs[j]] = make(map[string]int)
                    }
                    tbls[splitAssocs[i]][splitAssocs[j]] = 1
                    tbls[splitAssocs[j]][splitAssocs[i]] = 1
                }

            }

        } else {
            _, ok := tbls[t]            
            if !ok{
                tbls[t] = make(map[string]int)
            }
        }

    }

    fmt.Println(tbls)
}

关于go - 内部循环定义父链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106971/

相关文章:

arrays - 如何从 C 函数返回 C 结构数组?

go - 范围/CIDR 中的剩余 IP

go - 如何仅调用具有注释或标签的特定函数

go - 如何列出接口(interface)类型中的方法名称?

docker - 使用docker时在Goland中配置GOROOT

golang 从 net.TCPConn 中以 4 个字节作为消息分隔读取字节

go - 通过特定键的 GetStateByPartialCompositeKey 不起作用

go - 将 RSA PrivateKey PEM 写入 golang 文件

go - 将参数传递给 GoLang 中的 filepath.Glob 函数

http - 使用 net/http FileServer 服务文件导致 404