go 工作学习总结

1、Go语言中一个函数返回类型为 map[string]interface{},如何将其强制转换为string类型呢?

如题,返回result map[string]interface{}
1、尝试使用result.(string)强制转换,发现会报错,如下图
在这里插入图片描述
2、尝试使用Marshal和Unmarshal,也失败,如下图
在这里插入图片描述
在这里插入图片描述
解决:
Marshal为[]byte类型后直接转换为string,不需要再次Unmarshal
在这里插入图片描述
https://ask.csdn.net/questions/759674

2、Go下encoding/json的Indent()接口以及Marshal()和MarshalIndent()的区别

通俗来讲,Indent()对读的结果做了一些处理,简单说就是对Json 多了一些格式处理。
而MarshalIndent()函数实现里就调用了Indent().

js,_ := json.Marshal(&person)
jsIndent,_ := json.MarshalIndent(&person, "", "\t")
fmt.Println("\njs:\n",string(js), "\n\njsIndent:\n",string(jsIndent)

打印:
在这里插入图片描述
MarshalIndent还可以设置前缀不为空

jsIndent,_ := json.MarshalIndent(&person, "haha", "\t")

结果:
在这里插入图片描述
MarshalIndent 方法的代码如下:

// MarshalIndent is like Marshal but applies Indent to format the output.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
    b, err := Marshal(v)
    if err != nil {
        return nil, err
    }
    var buf bytes.Buffer
    err = Indent(&buf, b, prefix, indent)
    if err != nil {
        return nil, err
    }
    return buf.Bytes(), nil
}

相比于Marhsal()的区别就在于读结果做了Indent 的处理: Indent 的代码有点长,简单说就是对Json 多了一些格式处理:

// Indent appends to dst an indented form of the JSON-encoded src.
// Each element in a JSON object or array begins on a new,
// indented line beginning with prefix followed by one or more
// copies of indent according to the indentation nesting.
// The data appended to dst does not begin with the prefix nor
// any indentation, to make it easier to embed inside other formatted JSON data.
// Although leading space characters (space, tab, carriage return, newline)
// at the beginning of src are dropped, trailing space characters
// at the end of src are preserved and copied to dst.
// For example, if src has no trailing spaces, neither will dst;
// if src ends in a trailing newline, so will dst.
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
    origLen := dst.Len()
    var scan scanner
    scan.reset()
    needIndent := false
    depth := 0
    for _, c := range src {
        scan.bytes++
        v := scan.step(&scan, c)
        if v == scanSkipSpace {
            continue
        }
        if v == scanError {
            break
        }
        if needIndent && v != scanEndObject && v != scanEndArray {
            needIndent = false
            depth++
            newline(dst, prefix, indent, depth)
        }
 
        // Emit semantically uninteresting bytes
        // (in particular, punctuation in strings) unmodified.
        if v == scanContinue {
            dst.WriteByte(c)
            continue
        }
 
        // Add spacing around real punctuation.
        switch c {
        case '{', '[':
            // delay indent so that empty object and array are formatted as {} and [].
            needIndent = true
            dst.WriteByte(c)
 
        case ',':
            dst.WriteByte(c)
            newline(dst, prefix, indent, depth)
 
        case ':':
            dst.WriteByte(c)
            dst.WriteByte(' ')
 
        case '}', ']':
            if needIndent {
                // suppress indent in empty object/array
                needIndent = false
            } else {
                depth--
                newline(dst, prefix, indent, depth)
            }
            dst.WriteByte(c)
 
        default:
            dst.WriteByte(c)
        }
    }
    if scan.eof() == scanError {
        dst.Truncate(origLen)
        return scan.err
    }
    return nil
}

处理格式:
在这里插入图片描述
学习链接:https://blog.csdn.net/judgejames/article/details/97278727

3、Go创建文件 os.Create()

package main
 
import (
	"fmt"
	"os"
)
 
func main() {
	// 创建文件
	fp, err := os.Create("./demo.txt")  // 如果文件已存在,会将文件清空。
	fmt.Println(fp, err)  // &{0xc000076780} <nil>
	fmt.Printf("%T", fp)  // *os.File 文件指针类型
 
	if err != nil {
		fmt.Println("文件创建失败。")
		//创建文件失败的原因有:
		//1、路径不存在  2、权限不足  3、打开文件数量超过上限  4、磁盘空间不足等
		return
	}
 
	// defer延迟调用
	defer fp.Close()  //关闭文件,释放资源。
}

https://blog.csdn.net/houyanhua1/article/details/88739691

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值