douqian1296 2016-09-23 20:26
浏览 83
已采纳

要构造的字符串数组

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. 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.

  • 写回答

1条回答 默认 最新

  • doutuosai3504 2016-09-23 21:01
    关注

    There is a handy strings.Fields function in strings package that helps to parse this kind of output. Go likes pragmatic approaches, so the naive implementation would be:

    • iterate over your array and split each line into fields with whitespace as separator
    • construct new ProcessInfo object from these fields
    • add this object to the array

    Assuming your array is named lines, just do something like this:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作