Home > Backend Development > Golang > Why Can\'t I Directly Convert Between Slices of Different Types in Go?

Why Can\'t I Directly Convert Between Slices of Different Types in Go?

Linda Hamilton
Release: 2024-12-03 14:36:12
Original
767 people have browsed it

Why Can't I Directly Convert Between Slices of Different Types in Go?

Type Conversion Restrictions in Go

Go enforces strict typing rules, which can prevent seemingly obvious conversions between slices of different types containing the same underlying elements. This restriction is evident in the following code:

package main

import "fmt"

type Card string
type Hand []Card

func NewHand(cards []Card) Hand {
    hand := Hand(cards)
    return hand
}

func main() {
    value := []string{"a", "b", "c"}
    firstHand := NewHand(value)
    fmt.Println(firstHand)
}
Copy after login

Despite the similarity between []string and []Card, the compiler reports an error:

cannot use value (type []string) as type []Card in argument to NewHand
Copy after login

Rationale

Go's specification prohibits this conversion to prevent accidental type conversions between unrelated types that coincidentally share the same structure.

Solutions

  • Safe Copy: The recommended approach is to copy the contents of the slice to the desired type.
  • Unsafe Pointer Conversion (Unsafe): This technique bypasses the type system and allows direct conversion using the unsafe package, but it should be used with caution.
value := []string{"a", "b", "c"}
cards := *(*[]Card)(unsafe.Pointer(&value))
firstHand := NewHand(cards)
Copy after login

The above is the detailed content of Why Can\'t I Directly Convert Between Slices of Different Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template