登录
首页 >  Golang >  Go问答

如何在 Go 中使用字符串文字

来源:stackoverflow

时间:2024-04-16 20:36:35 467浏览 收藏

今天golang学习网给大家带来了《如何在 Go 中使用字符串文字》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

在 go 模板中,我想用变量替换下面的字符串:

bot := digitalassistant{"bobisyouruncle", "teamawesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "[email protected]"}

假设我想用变量 input 替换 bobisyouruncle

我该怎么做?

在 js 中这很简单:

bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "[email protected]"}

解决方案


在 go 中,不存在像 es6 那样的字符串模板文字。但是,您绝对可以使用 fmt.Sprintf 执行类似的操作。

fmt.sprintf("hello %s! happy coding.", input)

在你的情况下,它是:

bot := digitalassistant{
    fmt.sprintf("%s", input),
    "teamawesome",
    "awesomebotimagename",
    "0.1.0",
    1,
    8000,
    "health",
    "[email protected]",
}

顺便说一句,这是一个奇怪的问题。为什么需要在像 ${input} 这样非常简单的字符串上使用字符串模板文字?为什么不只是 input

编辑1

我不能只输入输入,因为 go 给出错误无法使用输入(类型 []byte)作为字段值中的类型字符串

[]byte 可转换为字符串。如果您的 input 类型是 []byte,只需将其写为 string(input) 即可。

bot := digitalassistant{
    string(input),
    "teamawesome",
    "awesomebotimagename",
    "0.1.0",
    1,
    8000,
    "health",
    "[email protected]",
}

编辑2

如果值是 int,为什么我不能做同样的事情?因此,对于括号 1 和 8000 中的值,我不能只执行 int(numberinput)int(portinput) ,否则我会收到错误 cannot use numberinput (type []byte) as the type int in field value

可以使用 explicit conversion T(v) 实现从 string[]byte 的转换,反之亦然。但是,此方法并不适用于所有类型。

例如,要将 []byte 转换为 int 需要更多的努力。

// convert `[]byte` into `string` using explicit conversion
valueInString := string(bytesData) 

// then use `strconv.Atoi()` to convert `string` into `int`
valueInInteger, _ := strconv.Atoi(valueInString) 

fmt.Println(valueInInteger)

我建议查看 go spec: conversion

本篇关于《如何在 Go 中使用字符串文字》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>