草庐IT

go - 什么是 ...interface{} 作为参数

coder 2023-06-27 原文

我指的是 http://golang.org/pkg/log/ 上 func Printf 的源代码

func Printf(format string, v ...interface{})
Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.

我有两个问题:

  1. 什么是“...”?
  2. ...interface{} 是什么意思?

非常感谢

最佳答案

这并不是具体要走的路,所以与其他回答者不同,我会走更一般的路线。

关于变量参数(...)

... 在这里,称为“省略号”,表示函数可以接收可变数量的参数,通常称为 varargs(或 var-args,或其他拼写)。这称为 variadic function .

简单的说,根据下面的签名:

func Printf(format string, v ...interface{}) (n int, err error) {}

Printf 将期望类型为 string 的第一个参数,然后是类型为 interface{} 的 0 到 N 个参数。下一节将详细介绍该类型。

虽然提供任意数量的参数的能力看起来非常方便,并且在这里没有进入太多细节以避免偏离主题的风险,但它有一些警告,具体取决于语言的实现:

  • 内存消耗增加,
  • 可读性下降,
  • 代码安全性降低。

我会留给您从上面的资源中查找原因。

关于空接口(interface)(interface{})

这个语法位更特定于 Go,但提示在名称中:interface

接口(interface)(或更接近 Go 的范例,协议(protocol))是一种定义其他对象遵守的契约的类型。根据这个Wikipedia关于 interfaces in computing 的文章(粗体字强调,斜体字更正):

In object-oriented languages, **the term "interface" is often used to define an abstract type that contains no data, but exposes behaviors defined as methods. A class having all the methods corresponding to that interface is said to implement that interface. Furthermore, a class can [in some languages]) implement multiple interfaces, and hence can be of different types at the same time.

An interface is hence a type definition; anywhere an object can be exchanged (in a function or method call) the type of the object to be exchanged can be defined in terms of an interface instead of a specific class. This allows later code to use the same function exchanging different object types; _[aiming to be]_ generic and reusable.

现在回到 Go 的空接口(interface)

Go 是一种强类型语言,具有多种内置类型,包括 Interface Types ,他们在当前 (1.1) 语言规范中将其描述为 gollows:

An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.

再往下,您将了解您在 Printf 的签名 interface{} 中看到的结构(我的粗体强调):

A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:

interface{}

这基本上意味着任何类型都可以表示为“空接口(interface)”,因此 Printf 可以接受这些可变参数的任何类型的变量。


与其他语言的快速比较

历史上,名称 printf来自 C 函数和同名二进制文件,printf 意思是“打印格式”,尽管早期语言中有可变参数打印函数,可变参数函数用于许多其他场景。但是,printf 通常被认为是这种用法的主要示例。它在 C 中的签名是:

int printf(const char *format, ...);

由于它们的实用性,varargs 和 printf 熟悉的面孔出现在大多数语言中......

在 Java 中,printf 以多种形式存在,特别是来自 PrintStream类:

public PrintStream printf(String format, Object... args)

其他一些语言不关心指定变量参数并将其隐式化,例如在 JavaScript 中,arguments函数中的特殊变量允许访问传递给函数的任何参数,无论它们是否与原型(prototype)匹配。

console.log()方法将是一个类似于 printf 的示例,为了清楚起见,扩展了以下伪签名(但实际上只是使用 arguments):

console.log(obj1 [, obj2, ..., objN);
console.log(msg [, subst1, ..., substN);

关于go - 什么是 ...interface{} 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629294/

有关go - 什么是 ...interface{} 作为参数的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  8. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  9. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  10. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

随机推荐