Go -使用通用方法将数据加载到三个Struct中

vd8tlhqk  于 2023-08-01  发布在  Go
关注(0)|答案(1)|浏览(135)

我想用一个解析文件的方法(指针)将数据加载到三个结构体中。我是新来的。

type a struct {
    a string
}

type b struct {
    b string
}

type c struct {
    c string
}

func main() {
    parse_file(filename)
}

//In below method, *l not sure how to define which can include 3 struct
func (l *l)parse_file(filename string) {
    // open a file line by line
    // if the line has value a then load into Struct a
    //If the line has value b then load into Struct b
    //If the line has value C then load into Struct c
}

字符串

a0zr77ik

a0zr77ik1#

您可以定义一个结构体,它嵌入其他3个结构体
查看样品
test.txt

a - This is A
b - This is B
c - This is C

字符串
编码

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

type a struct {
    a string
}

type b struct {
    b string
}

type c struct {
    c string
}

type l struct {
    a
    b
    c
}

func main() {

    l := &l{}
    filename := "test.txt"
    l.parse_file(filename)

    fmt.Println("A : ", l.a)
    fmt.Println("B : ", l.b)
    fmt.Println("C : ", l.c)
}

// In below method, *l not sure how to define which can include 3 struct
func (l *l) parse_file(filename string) {
    // open a file
    file, err := os.Open(filename)
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // read line by line
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        switch {
        // if the line has value a then load into Struct a
        case strings.HasPrefix(line, "a -"):
            // add the data to the a object
            l.a = a{
                a: line,
            }

        //If the line has value b then load into Struct b
        case strings.HasPrefix(line, "b -"):
            // add the data to the b object
            l.b = b{
                b: line,
            }

        //If the line has value C then load into Struct c
        case strings.HasPrefix(line, "c -"):
            // add the data to the c object
            l.c = c{
                c: line,
            }
        }
    }
}


如果要删除前缀a -b -c -,则可以使用TrimPrefix将其删除

line := strings.TrimPrefix(line, "a -")

相关问题