Devdit
 

cannot use n (type []int) as type []string in argument to sort.Strings Go คือ วิธีแก้ไข

868

ฝึกเขียนภาษา Go (Golang) สำหรับเรียงลำดับข้อมูล แต่รันแล้วไม่ผ่านขึ้นข้อความว่า cannot use n (type []int) as type []string in argument to sort.Strings แบบนี้ต้องแก้ไขอย่างไร

package main
import (
    "fmt"
	"sort"
)

func main() {
	n := []int{4, 3, 0, 9}
	sort.Strings(n)
	fmt.Println( n )
}

 

วิธีแก้ไข

ปัญหานี้เกิดจากตัวแปร array เป็นชนิด int กรณีต้องการเรียงลำดับข้อมูลชนิดตัวเลข แนะนำให้ใช้คำสั่ง sort.Ints แทน sort.Strings

package main
import (
    "fmt"
	"sort"
)

func main() {
	n := []int{4, 3, 0, 9}
	sort.Ints(n)
	fmt.Println( n )
}
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ