0
0
GoHow-ToBeginner · 3 min read

How to Create String in Go: Syntax and Examples

In Go, you create a string by assigning text enclosed in double quotes to a variable using var or :=. For example, name := "Hello" creates a string variable named name with the value "Hello".
📐

Syntax

To create a string in Go, you declare a variable and assign it text inside double quotes. You can use var with a type or use short declaration := which infers the type automatically.

  • var s string = "text" declares a string variable s.
  • s := "text" is a shorter way to declare and assign.
go
var s string = "Hello, Go!"
s2 := "Welcome to strings"
💻

Example

This example shows how to create string variables and print them to the console.

go
package main

import "fmt"

func main() {
    var greeting string = "Hello, World!"
    name := "Go Learner"
    fmt.Println(greeting)
    fmt.Println("Welcome, " + name)
}
Output
Hello, World! Welcome, Go Learner
⚠️

Common Pitfalls

Common mistakes include using single quotes instead of double quotes, which are for characters, not strings. Also, forgetting to initialize a string variable will give it an empty string by default, not null.

Strings in Go are immutable, so you cannot change characters directly by index.

go
package main

import "fmt"

func main() {
    // Wrong: single quotes are for rune (character), not string
    // s := 'hello' // This causes a compile error

    // Correct:
    s := "hello"
    fmt.Println(s)
}
Output
hello
📊

Quick Reference

Here is a quick summary of creating strings in Go:

ConceptExampleNotes
Declare with varvar s string = "text"Explicit type declaration
Short declarations := "text"Type inferred automatically
Empty stringvar s stringDefaults to empty string ""
Concatenates1 + s2Use + to join strings
Immutables[0] = 'a' // errorStrings cannot be changed by index

Key Takeaways

Create strings by assigning text in double quotes to variables using var or :=
Use double quotes for strings; single quotes are for single characters (runes).
Strings are immutable; you cannot change characters by index after creation.
Uninitialized string variables default to an empty string "".
Use + to concatenate strings easily.