Golang中Print函数从开头开始打印的问题

Golang中Print函数从开头开始打印的问题 image

我想在URL的末尾添加一个“/”字符,以便CURL能够正常工作(没有它就无法工作),但当我添加它时,不知为何它被添加到了开头。我不知道发生了什么。

2 回复

请确保您移除了 id,很可能有一个 \r 现在在困扰您。

使用 fmt.Printf("%#v", a) 可能会看得更清楚。

fmt.Printf("%#v", a)

更多关于Golang中Print函数从开头开始打印的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


从你提供的图片和描述来看,问题出在字符串拼接和打印的顺序上。Print函数本身不会导致字符串被添加到开头,问题很可能是在构建URL字符串时发生的。以下是可能的原因和示例代码:

问题分析

  1. 字符串拼接顺序错误:你可能在拼接URL时错误地将"/"放在了前面。
  2. 缓冲区或变量重用:可能之前的字符串内容残留在缓冲区中。

示例代码

假设你有一个基础URL,并想在其末尾添加"/":

package main

import "fmt"

func main() {
    baseURL := "https://example.com/api/v1/resource"
    
    // 错误的方式:将"/"加在了开头
    wrongURL := "/" + baseURL
    fmt.Print("Wrong URL: ", wrongURL) // 输出: /https://example.com/api/v1/resource
    
    // 正确的方式:将"/"加在末尾
    correctURL := baseURL + "/"
    fmt.Print("Correct URL: ", correctURL) // 输出: https://example.com/api/v1/resource/
}

更完整的示例

如果你是从多个部分构建URL:

package main

import (
    "fmt"
    "strings"
)

func main() {
    base := "https://example.com"
    path := "api/v1/resource"
    
    // 使用 strings.Join 确保正确拼接
    url := strings.Join([]string{base, path}, "/")
    url += "/" // 在末尾添加斜杠
    
    fmt.Print("Final URL: ", url) // 输出: https://example.com/api/v1/resource/
}

使用 fmt.Sprintf

package main

import "fmt"

func main() {
    baseURL := "https://example.com/api/v1/resource"
    urlWithSlash := fmt.Sprintf("%s/", baseURL)
    fmt.Print("URL: ", urlWithSlash) // 输出: https://example.com/api/v1/resource/
}

检查你的代码中构建URL的部分,确保是在字符串末尾添加"/",而不是开头。Print函数只是输出字符串的当前内容,不会修改字符串的顺序。

回到顶部