Convert data to base64 encode in go

huangapple go评论67阅读模式
英文:

Convert data to base64 encode in go

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Go编程语言还不熟悉,我在我的代码中遇到了一个问题。这是我的示例代码:

a := genreAPI{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println("a的值为:", a)

当前的输出结果是:a的值为:[{Pop} {Rock}]

如何实现以下输出结果:
a的值为:[{UG9w} {Um9jaw==}]
这是一个Base64编码的结果。

英文:

I am new to go programming language and I'm stock on this scenario on my code.
Here's my example code:

a := genreAPI{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println("Value of a :", a)

The current output is: Value of a : [{Pop} {Rock}]

How can I achieved an output like this:
Value of a : [{UG9w} {Um9jaw==}]
which is a base64 encode?

答案1

得分: 6

我不确定文档中到底哪部分不清楚。它不仅有一个清晰的名称来解释方法的作用,还有一个示例。

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := []byte("Pop")
	str := base64.StdEncoding.EncodeToString(data)
	fmt.Println(str) // UG9w
}

Go Playground

英文:

I am not sure what exactly is not clear from the documentation. Not only it has a clear name which explains states what the method is doing, it also has an example.

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := []byte("Pop")
	str := base64.StdEncoding.EncodeToString(data)
	fmt.Println(str) // UG9w
}

<kbd>Go Playground</kbd>

答案2

得分: 0

你可以通过为你的类型提供一个String()方法来自定义打印函数的输出。可以为整个Genre类型或者只为名称变量提供。

示例:

package main

import (
	"encoding/base64"
	"fmt"
)

type Base64String string

func (b Base64String) String() string {
	return base64.StdEncoding.EncodeToString([]byte(b))
}

type Genre struct {
	Name Base64String
}

func main() {
	a := []Genre{Genre{"Pop"}, Genre{"Rock"}}
	fmt.Println(a)                 // 输出 [{UG9w} {Um9jaw==}]
	fmt.Println(string(a[0].Name)) // 输出 Pop
}
英文:

You can customise the output of print functions by providing a String() method for your type. Either for the whole Genre or just for the name variable.

Example:

package main

import (
	&quot;encoding/base64&quot;
	&quot;fmt&quot;
)

type Base64String string

func (b Base64String) String() string {
	return base64.StdEncoding.EncodeToString([]byte(b))
}

type Genre struct {
	Name Base64String
}

func main() {
	a := []Genre{Genre{&quot;Pop&quot;}, Genre{&quot;Rock&quot;}}
	fmt.Println(a)                 // prints [{UG9w} {Um9jaw==}]
	fmt.Println(string(a[0].Name)) // prints Pop
}

huangapple
  • 本文由 发表于 2015年6月11日 15:36:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/30774503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定