title: How to coerce _string-type_ to _fixed-length string-type_ in Go?
body: <p>I have a simple program to open a text file with two space-separated elements per line (first name and last name). Then, I put first-name and last-name in to a struct (T), which goes in a slice of such structs ([ ]T).</p>
  <p>There is a catch, first-name and last-name <strong>must</strong> be limited by 20 characters. When reading the text-file, I'm unable to coerce the text to be of that fixed-length. <strong>How can I coerce a general string into a &quot;maximum-20char-string&quot;?</strong></p>
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      &quot;bufio&quot;
      &quot;fmt&quot;
      &quot;os&quot;
      &quot;strings&quot;
  )
  
  type T struct {
      fname [20]string
      lname [20]string
  }
  
  func main() {
      // Ask for file name (fn)
      fmt.Println(&quot;Enter file name, e.g.: 'names.txt'&quot;)
      var fn string
      _, _ = fmt.Scan(&amp;fn)
  
      // Open file
      file, err := os.Open(fn)
      if err != nil {
          fmt.Println(err)
      }
      defer file.Close()
  
      // Create a slice, in which the T constructs will be populated.
      var slice []T
  
      // Counter for each line
      i := 0
  
      // Read each line and iterate on it
      scanner := bufio.NewScanner(file)
      for scanner.Scan() {
          fmt.Println(scanner.Text())
          strline := scanner.Text()
          // words := strings.Split(strline, &quot; &quot;)
          // var words [20]string
          words := strings.Fields(strline)
          // fmt.Println(words, len(words))
          slice[i] = T{fname: words[0], lname: words[1]}
          i = i + 1
      }
  
      if err := scanner.Err(); err != nil {
          fmt.Println(err)
      }
  
      // return slice with T-type elements
      fmt.Println(slice)
  }
  </code></pre>
  <p>In the terminal,</p>
  <pre class="lang-sh prettyprint-override"><code>go build read.go
  </code></pre>
  <pre class="lang-sh prettyprint-override"><code># command-line-arguments
  ./read.go:43:23: cannot use words[0] (variable of type string) as type [20]string in struct literal
  ./read.go:43:40: cannot use words[1] (variable of type string) as type [20]string in struct literal
  </code></pre>