zoukankan      html  css  js  c++  java
  • golang 中奇怪的空切片

    本文中介绍一个奇怪现象,一个空列表(或切片),却可以打印出列表中的内容。

    以下代码中,在一个json字符串中,定义一个列表,列表中有一个空字符串。

    接着,将json字符串解析到结构体中,最后,打印结构体中的字符串列表。

    package main
    
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Host struct {
        IPList []string
    }
    
    func main() {
    
        b := []byte(`{"IPList": [""]}`)
    
        h := Host{}
    
        err := json.Unmarshal(b, &h)
        if err != nil {
            fmt.Println("Umarshal failed:", err)
            return
        }
    
    
        fmt.Println("host:", h)
        fmt.Println("IPList:", h.IPList, ", len:", len(h.IPList))
        for _,ip := range h.IPList {
            fmt.Println("ip:", ip, ", len:", len(ip))
        }
    }
    

    output:

    host: {[]}
    IPList: [] , len: 1
    ip: , len: 0

    从输出可以看到,IPList是空列表,在遍历时,却可以打印出内容--空字符串。

    Just try, don't shy.
  • 相关阅读:
    第1章 数据结构绪论
    收集的名言警句
    Asp.net MVC知识积累
    我的书单
    ASP.NET Web API
    贱人语录
    正则表达式入门
    Lucene 3.0
    Solr之java操作
    Elasticsearch
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/14398213.html
Copyright © 2011-2022 走看看