简体   繁体   English

要转换为struct的字符串数组

[英]array of strings to go struct

This is the command that i execute 这是我执行的命令

$ ps -e
  PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
 4372       1    4372       4372  ?         197608 03:44:57 /usr/bin/mintty
 6476    4372    6476       6208  pty0      197608 03:44:58 /usr/bin/bash
14484    6476   14484      12888  pty0      197608 13:23:48 /usr/bin/ps

I get 1d array of strings using bufio scanner.scanLines. 我使用bufio获得1d字符串数组。 I need to convert this into array of structs: 我需要将其转换为结构数组:

type ProcessInfo struct {
    PID string `json:"PID"`
    PPID string `json:"PPID"`
    PGID string `json:"PGID"`
    WINPID string    `json:"WINPID"`
    TTY   string `json:"TTY"`
    UID string `json:"UID"`
    STIME string `json:"STIME"`
    COMMAND string `json:"COMMAND"`
}

Any help would be appreciated. 任何帮助,将不胜感激。

There is a handy strings.Fields function in strings package that helps to parse this kind of output. 字符串包中有一个方便的strings.Fields函数,有助于解析这种输出。 Go likes pragmatic approaches, so the naive implementation would be: Go喜欢实用的方法,所以天真的实现将是:

  • iterate over your array and split each line into fields with whitespace as separator 迭代您的数组并将每一行拆分为以空格作为分隔符的字段
  • construct new ProcessInfo object from these fields 从这些字段构造新的ProcessInfo对象
  • add this object to the array 将此对象添加到数组中

Assuming your array is named lines , just do something like this: 假设您的数组是命名lines ,只需执行以下操作:

var pinfos []ProcessInfo
for _, line := range lines {
    fields := strings.Fields(line)

    pi := ProcessInfo{
        PID:     fields[0],
        PPID:    fields[1],
        PGID:    fields[2],
        WINPID:  fields[3],
        TTY:     fields[4],
        UID:     fields[5],
        STIME:   fields[6],
        COMMAND: fields[7],
    }

    pinfos = append(pinfos, pi)
}

See the whole code here: https://play.golang.org/p/wo8FFiYabA 请在此处查看完整代码: https//play.golang.org/p/wo8FFiYabA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM