Skip to content

strings: Join drops trailing empty strings #67604

Description

@jsumners

Go version

1.22

Output of go env in your module/workspace:

Whatever go.dev/play has.

What did you do?

https://go.dev/play/p/lRtKx16rXk1

package main

import (
	"fmt"
	"strings"
)

func main() {
	lines := []string{
		"line 1",
		"",
		"line 2",
		"",
		"line 3",
		"",
	}

	joined := strings.Join(lines[0:4], "\n")

	foundCount := 0
	for _, c := range joined {
		if c == 0x0a {
			foundCount += 1
		}
	}

	fmt.Printf("found %d line feeds, expected 4", foundCount)
}

What did you see happen?

strings.Join skipped adding the intended final joining character.

What did you expect to see?

strings.Join would join all elements passed to it with the provided joining character.

Activity

  1. fzipp commented on May 23, 2024

    @fzipp
    Contributor

    strings.Join skipped adding the intended final joining character.

    You're cutting off the last two elements yourself: lines[0:4]

  2. jsumners commented on May 23, 2024

    @jsumners
    Author

    The result should be line 1\n\nline 2\n\n.

  3. randall77 commented on May 23, 2024

    @randall77
    Contributor

    A strings.Join of 4 items should have 3 separators, not 4.

  4. locked and limited conversation to collaborators on May 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions