github.com/searKing/golang/go@v1.2.117/unsafe/conv_go1.19.go (about)

     1  // Copyright 2023 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build !go1.20
     6  
     7  package unsafe
     8  
     9  import (
    10  	"unsafe"
    11  )
    12  
    13  // StringToBytes converts string to byte slice without a memory allocation.
    14  func StringToBytes(s string) []byte {
    15  	return *(*[]byte)(unsafe.Pointer(
    16  		&struct {
    17  			string
    18  			Cap int
    19  		}{s, len(s)},
    20  	))
    21  }
    22  
    23  // BytesToString converts byte slice to string without a memory allocation.
    24  func BytesToString(b []byte) string {
    25  	return *(*string)(unsafe.Pointer(&b))
    26  }