dsfsdfsdfsdfsdf45454 2018-09-18 21:31
浏览 4

如何从文件填充结构

I have a struct that is designed like this:

type UrlData struct {
    As int 
    Iso string 
}

I instantiate it and after that I read a text file (see below) so as to check if certain struct field is equal to a value from the txt file (yes, I know that it would be much easier to compare explicitly, but reading the data from file is the requirement to be met)

The txt file has the following format:

as 646
iso us

When reading the txt file, I want to know if the *UrlData.As field (in the instantiated item) is equal to the value from file, i.e. 646.

The problem is I don't know how to match current field from the txt file with the name of the struct field. What is the most adequate way to do that?

  • 写回答

1条回答 默认 最新

  • dongtuo5611 2018-09-18 21:41
    关注

    You will need to implement a mechanism which can determine which field is named on the line and match this against the corresponding field in the structure. The field identification is easy: use strings.Split on a line read from the file, split on the space, and retrieve the first value.

    Looking this up in the struct can take a couple of approaches. The simplest would explicitly test this in a conditional or similar (I have avoided showing code to read the file, as the crux of your question seems to be the matching with the struct values):

    // Struct
    var myStruct *UrlData = // some instantiation
    
    // Read line from file
    line = // TODO
    
    // Determine the field
    parts := strings.Split(line, " ")
    name, value := parts[0], parts[1]
    
    // Look up the fields in the struct
    switch name {
    case "as":
            return myStruct.As == value
    case "iso":
            return myStruct.Iso == value
    }
    

    It is also possible to use reflection to dynamically look up the struct field from the name in the file, but this will be more complex and should be avoided until you require a truly generic solution (and even then best avoided - reflection is not clear code!).

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?